<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @selection-change="selectionChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button
          size="small"
          type="primary"
          icon="el-icon-download"
          @click="handleAllocate"
          >导出
        </el-button>
        <el-button
          type="danger"
          size="small"
          icon="el-icon-delete"
          plain
          @click="handleDelete"
          >删 除
        </el-button>
      </template>
      <template slot-scope="scope" slot="menuBtn">
        <el-dropdown-item>
          <el-popconfirm
            confirm-button-text="确定"
            cancel-button-text="取消"
            @confirm="handleRealname(scope.row.id)"
            icon-color="red"
            title="您确认要同步实名吗？"
            placement="top"
          >
            <div class="el-icon-refresh" slot="reference">&nbsp;同步实名</div>
          </el-popconfirm>
        </el-dropdown-item>
        <el-dropdown-item>
          <el-popconfirm
            confirm-button-text="确定"
            cancel-button-text="取消"
            @confirm="handleSimStatus(scope.row.id, scope.row.lifecycleStatus)"
            icon-color="red"
            :title="
              scope.row.lifecycleStatus != 4
                ? '您确认要停机吗？'
                : '您确认要复机吗？'
            "
            placement="top"
          >
            <div
              v-if="scope.row.lifecycleStatus != 4"
              class="el-icon-phone"
              slot="reference"
            >
              &nbsp;申请停机
            </div>
            <div
              v-if="scope.row.lifecycleStatus == 4"
              class="el-icon-phone-outline"
              slot="reference"
            >
              &nbsp;申请复机
            </div>
          </el-popconfirm>
        </el-dropdown-item>
      </template>
    </avue-crud>

    <!-- 导出弹窗 -->
    <el-dialog
      title="导出"
      :visible.sync="dialogVisible"
      append-to-body
      width="35%"
      :before-close="handleClose"
    >
      <el-form
        ref="distribution"
        :model="distribution"
        :rules="distrules"
        label-width="120px"
      >
        <el-form-item label="客户" prop="tenantId">
          <el-select
            v-model="distribution.tenantId"
            placeholder="请选择客户"
            size="mini"
            style="width: 90%"
          >
            <el-option
              v-for="(item, index) in tenantlist"
              :label="item.tenantName"
              :value="item.tenantId"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="导出类型" prop="exportType">
          <el-select
            v-model="distribution.exportType"
            placeholder="请选择客户"
            size="mini"
            style="width: 90%"
          >
            <el-option
              v-for="(item, index) in exportTypelist"
              :label="item.dictValue"
              :value="item.dictKey"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始/结束号码" prop="numbers">
          <el-col :span="10">
            <el-form-item prop="numStart">
              <el-input
                v-model="distribution.numStart"
                placeholder="请输入开始号码"
                size="mini"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col style="text-align: center" :span="2">-</el-col>
          <el-col :span="10">
            <el-form-item prop="numEnd">
              <el-input
                v-model="distribution.numEnd"
                placeholder="请输入结束号码"
                size="mini"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onSubmit" size="small">
          <i class="el-icon-circle-plus-outline" style="padding-right: 5px"></i>
          导 出</el-button
        >
        <el-button @click="handleClose" size="small">
          <i class="el-icon-circle-close" style="padding-right: 5px"></i> 取
          消</el-button
        >
      </span>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  getList,
  add,
  getDetail,
  remove,
  update,
  tenant,
  user,
  exporttype,
  syncRealNameStatus,
  updateSimStatus,
} from "@/api/communication/outbound";
import { mapGetters } from "vuex";
import { getToken } from "@/util/auth";
export default {
  data() {
    var reg = /[A-Za-z]/i;
    var starts = (rule, value, callback) => {
      if (this.distribution.numEnd == "" || this.distribution.numStart == "") {
        callback(new Error("开始号码结束号码均不能为空"));
      } else if (
        this.distribution.numEnd < 0 ||
        this.distribution.numStart < 0
      ) {
        callback(new Error("开始号码结束号码均不能为负数"));
      } else if (
        Number(this.distribution.numStart) > Number(this.distribution.numEnd)
      ) {
        callback(new Error("开始号码必须小于结束号码"));
      } else if (
        reg.test(this.distribution.numStart) == true ||
        reg.test(this.distribution.numEnd) == true
      ) {
        callback(new Error("开始结束号码中包含字母，请选择其他导出类型"));
      } else {
        callback();
      }
    };
    return {
      form: {},
      query: {},
      iform: {
        type: null, //租户/客户
        tenantId: null, //租户
        userId: null, //客户
      },
      status: "",
      dialogVisible: false, //分拨弹窗布尔
      selectionList: [],
      tenantlist: [], //租户下拉
      userlist: [], //用户下拉

      //导出
      distribution: {
        tenantId: "", //租户id
        numStart: "", //开始号码
        numEnd: "", //结束号码
        exportType: "", //导出类型
      },
      loading: true,
      distrules: {
        tenantId: [
          { required: true, message: "请选择客户", trigger: "change" },
        ],
        numbers: [{ required: true, validator: starts, trigger: "blur" }],
        exportType: [
          { required: true, message: "请选择导出类型", trigger: "change" },
        ],
      },
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      option: {
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        searchIcon: true,
        addBtn: true,
        viewBtn: true,
        delBtn: true,
        dialogDrag: true,
        columnBtn: false,
        selection: true,
        dialogClickModal: false,
        dialogWidth: "60%",
        menuType: "menu",
        menuWidth: "120",
        column: [
          {
            label: "主键id",
            prop: "id",
            width: 180,
            addDisplay: false,
            editDisplay: false,
            search: true,
            rules: [
              {
                required: true,
                message: "请输入id",
                trigger: "blur",
              },
            ],
          },
          {
            label: "租户名称",
            prop: "tenantId",
            type: "select",
            dicUrl: "/api/iot-system/tenant/fillData",
            props: {
              label: "tenantName",
              value: "tenantId",
            },
            dataType: "String",
            span: 12,
            labelWidth: 130,
            width: 140,
            search: true,
            rules: [
              { required: true, message: "请选择租户名称", trigger: "change" },
            ],
          },
          {
            label: "用户名称",
            prop: "userId",
            type: "select",
            dicUrl: "/api/iot-system/user/fillData",
            formatter: (val, value, label) => {
              if (value == -1) {
                return "-";
              } else {
                return `${label}`;
              }
            },
            props: {
              label: "account",
              value: "id",
            },
            dataType: "String",
            span: 12,
            labelWidth: 130,
            width: 70,
            search: false,
            rules: [
              { required: true, message: "请选择用户名称", trigger: "change" },
            ],
          },
          {
            label: "通道名称",
            prop: "channelId",
            type: "select",
            dicUrl: "/api/iot-sim/channel/fillData",
            props: {
              label: "name",
              value: "id",
            },
            dataType: "String",
            span: 12,
            labelWidth: 130,
            width: 100,
            search: true,
            rules: [
              { required: true, message: "请选择通道名称", trigger: "change" },
            ],
          },
          {
            label: "流量池名称",
            prop: "flowPoolId",
            type: "select",
            dataType: "String",
            span: 12,
            labelWidth: 130,
            searchLabelWidth: 110,
            width: 110,
            search: true,
            display: true,
            dicUrl: "/api/iot-sim/flowpool/fillData?isSource=" + 2,
            formatter: (val, value, label) => {
              if (value == -1) {
                return "-";
              } else {
                return `${label}`;
              }
            },
            props: {
              label: "name",
              value: "id",
            },
            rules: [
              {
                required: true,
                message: "请选择流量池名称",
                trigger: "change",
              },
            ],
          },
          {
            label: "基础套餐",
            prop: "dataPlanId",
            type: "select",
            dicUrl: "/api/iot-sim/dataplan/fillData?isSource=" + 2,
            props: {
              label: "name",
              value: "id",
            },
            dataType: "String",
            span: 12,
            labelWidth: 130,
            searchLabelWidth: 110,
            width: 110,
            search: true,
            rules: [
              {
                required: true,
                message: "请选择基础套餐",
                trigger: "change",
              },
            ],
          },
          {
            label: "生命周期状态",
            prop: "lifecycleStatus",
            type: "select",
            dicUrl: "/api/iot-system/dict/dictionary?code=lifecycleStatus",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dataType: "number",
            span: 12,
            labelWidth: 130,
            searchLabelWidth: 110,
            width: 110,
            search: true,
            rules: [
              {
                required: true,
                message: "请选择生命周期状态",
                trigger: "change",
              },
            ],
          },
          {
            label: "卡类型",
            prop: "cardType",
            type: "select",
            dicUrl: "/api/iot-system/dict/dictionary?code=card_type",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dataType: "number",
            span: 12,
            labelWidth: 130,
            width: 70,
            search: true,
            rules: [
              { required: true, message: "请选择卡类型", trigger: "change" },
            ],
          },
          {
            label: "是否断网",
            prop: "offNetStatus",
            type: "select",
            dicUrl: "/api/iot-system/dict/dictionary?code=off_netStatus",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            formatter: (val, value, label) => {
              if (value == -1) {
                return "-";
              } else {
                return `${label}`;
              }
            },
            dataType: "number",
            span: 12,
            labelWidth: 130,
            width: 70,
            search: false,
            rules: [
              { required: true, message: "请选择是否断网", trigger: "change" },
            ],
          },
          {
            label: "断网类型",
            prop: "offNetType",
            type: "select",
            dicUrl: "/api/iot-system/dict/dictionary?code=off_netType",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dataType: "number",
            display: true,
            span: 12,
            formatter: (val, value, label) => {
              if (value == -1) {
                return "-";
              } else {
                return `${label}`;
              }
            },
            labelWidth: 130,
            width: 70,
            search: false,
            rules: [
              { required: true, message: "请选择断网类型", trigger: "change" },
            ],
          },
          {
            label: "实名状态",
            prop: "realNameStats",
            type: "select",
            dicUrl: "/api/iot-system/dict/dictionary?code=real_nameStats",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dataType: "number",
            span: 12,
            labelWidth: 130,
            width: 70,
            search: false,
            rules: [
              { required: true, message: "请选择实名状态", trigger: "change" },
            ],
          },
          {
            label: "达量断网阙值(M)",
            prop: "offNetThreshold",
            span: 12,
            labelWidth: 130,
            searchLabelWidth: 124,
            search: false,
            width: 120,
            rules: [
              {
                required: true,
                message: "请输入达量断网阙值",
                trigger: "blur",
              },
              {
                pattern: /^\d+(\.\d+)?$/,
                message: "请输入正确的阙值",
                trigger: "blur",
              },
            ],
          },
          {
            label: "批次号",
            prop: "batchNum",
            span: 12,
            labelWidth: 130,
            search: true,
            hide: true,
            addDisplay: false,
            rules: [
              {
                required: true,
                message: "请输入批次号",
                trigger: "blur",
              },
            ],
          },
          {
            label: "iccid",
            prop: "iccid",
            width: 150,
            span: 12,
            labelWidth: 130,
            search: true,
            rules: [
              {
                required: true,
                message: "请输入iccid",
                trigger: "blur",
              },
            ],
          },
          {
            label: "imsi",
            prop: "imsi",
            span: 12,
            width: 150,
            labelWidth: 130,
            search: true,
            addDisplay: false,
            rules: [
              {
                required: true,
                message: "请输入imsi",
                trigger: "blur",
              },
            ],
          },
          {
            label: "msisdn",
            prop: "msisdn",
            span: 12,
            width: 150,
            labelWidth: 130,
            addDisplay: false,
            search: true,
            rules: [
              {
                required: true,
                message: "请输入msisdn",
                trigger: "blur",
              },
            ],
          },
          {
            label: "剩余流量(M)",
            prop: "surplus",
            span: 12,
            type: "number",
            labelWidth: 130,
            hide: true,
            rules: [
              { required: true, message: "请输入剩余流量", trigger: "blur" },
              {
                pattern: /^\d+(\.\d+)?$/,
                message: "请输入正确的剩余流量",
                trigger: "blur",
              },
            ],
          },
          {
            label: "使用量(M)",
            prop: "usage",
            span: 12,
            labelWidth: 130,
            type: "number",
            hide: true,
            rules: [
              { required: true, message: "请输入使用量", trigger: "blur" },
              {
                pattern: /^\d+(\.\d+)?$/,
                message: "请输入正确的使用量",
                trigger: "blur",
              },
            ],
          },
          {
            label: "总量(M)",
            prop: "total",
            span: 12,
            labelWidth: 130,
            type: "number",
            hide: true,
            rules: [
              { required: true, message: "请输入总量", trigger: "blur" },
              {
                pattern: /^\d+(\.\d+)?$/,
                message: "请输入正确的总量",
                trigger: "blur",
              },
            ],
          },
        ],
      },
      data: [],
    };
  },
  watch: {
    "form.$channelId"() {
      const columns = this.findObject(this.option.column, "flowPoolId");
      if (this.form.$channelId != undefined) {
        if (this.form.$channelId.indexOf("电信") != -1) {
          columns.display = false;
          this.form.flowPoolId = "";
        } else {
          columns.display = true;
        }
      }
    },
    "form.$offNetStatus"() {
      const columns = this.findObject(this.option.column, "offNetType");
      if (this.form.$offNetStatus != undefined) {
        if (this.form.$offNetStatus == "未断网") {
          columns.display = false;
          this.form.offNetType = "";
        } else {
          columns.display = true;
        }
      }
    },
  },
  created() {
    this.tenantlists(); //租户下拉
    this.userlists(); //用户下拉
    this.exportTypelistlists(); //导出类型
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        // viewBtn: this.vaildData(this.permission.sourceApi_view, false),
        // editBtn: this.vaildData(this.permission.sourceApi_edit, false),
        // delBtn: this.vaildData(this.permission.sourceApi_delete, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  methods: {
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    //新增
    rowSave(row, done, loading) {
      console.log(this.form);
      add(row).then(
        () => {
          this.onLoad(this.page, this.query);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    //修改
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page, this.query);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    //删除
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page, this.query);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },
    //批量删除
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page, this.query);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs.crud.toggleSelection();
        });
    },
    //多选框
    selectionChange(list) {
      this.selectionList = list;
    },
    //多选框清除
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    //导出弹窗开启
    handleAllocate() {
      this.dialogVisible = true;
    },
    //导出弹窗关闭
    handleClose() {
      this.dialogVisible = false;
      this.$refs.distribution.resetFields();
    },
    //确认导出
    onSubmit() {
      this.$refs.distribution.validate((valid) => {
        if (valid) {
          window.open(
            `${this.baseUrl}/${
              this.apis
            }iot-sim/simcarddeliver/export-simCardDeliver?${
              this.website.tokenHeader
            }=${getToken()}&tenantId=${this.distribution.tenantId}&numStart=${
              this.distribution.numStart
            }&numEnd=${this.distribution.numEnd}&exportType=${
              this.distribution.exportType
            }`
          );
          this.dialogVisible = false;
          this.$refs.distribution.resetFields();
        }
      });
    },

    //租户下拉框
    tenantlists() {
      tenant().then((res) => {
        if (res.data.code == 200) {
          this.tenantlist = res.data.data;
        }
      });
    },
    //用户下拉框
    userlists() {
      user().then((res) => {
        if (res.data.code == 200) {
          this.userlist = res.data.data;
        }
      });
    },
    //导出类型
    exportTypelistlists() {
      exporttype().then((res) => {
        if (res.data.code == 200) {
          this.exportTypelist = res.data.data;
        }
      });
    },
    //选租户还是客户
    handleChange(e) {
      if (e == 1) {
        this.iform.type = 1;
        this.iform.userId = null;
      } else {
        this.iform.type = 2;
        this.iform.tenantId = null;
      }
    },
    //同步实名
    handleRealname(id) {
      syncRealNameStatus(id).then((res) => {
        console.log(res, 978);
        if (res.data.code == 200) {
          this.$message.success("同步成功");
          this.onLoad(this.page, this.query);
        } else {
          this.$message.error("同步失败");
        }
      });
    },
    //停机复机
    handleSimStatus(id, type) {
      if (type == 4) {
        updateSimStatus({ id: id, operType: 1 }).then((res) => {
          if (res.data.code == 200) {
            this.$message.success("复机成功");
            this.onLoad(this.page, this.query);
          } else {
            this.$message.error("复机失败");
          }
        });
      } else {
        updateSimStatus({ id: id, operType: 0 }).then((res) => {
          if (res.data.code == 200) {
            this.$message.success("停机成功");
            this.onLoad(this.page, this.query);
          } else {
            this.$message.error("停机失败");
          }
        });
      }
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
      });
    },
  },
};
</script>

<style></style>
