<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"
      @selection-change="selectionChange"
      @search-change="searchChange"
      @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="handleExport"
          >导出
        </el-button>
        <el-button
          type="primary"
          size="small"
          icon="el-icon-upload2"
          @click="handleImport"
          >导入</el-button
        >
        <el-button
          type="primary"
          size="small"
          icon="el-icon-share"
          @click="handleAllocate"
          >分拨</el-button
        >
        <!-- <el-button
          size="small"
          type="primary"
          icon="el-icon-sell"
          @click="delivery"
          >出&nbsp库</el-button> -->
      </template>
    </avue-crud>
    <!-- 导出    :upload-after="uploadAfter"-->
    <el-dialog title="导入" append-to-body :visible.sync="excelBox" width="40%">
      <avue-form
        :option="excelOption"
        v-model="excelForm"
        :upload-after="uploadAfter"
      >
        <!-- <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template> -->
      </avue-form>
    </el-dialog>
    <!-- 分拨弹窗 -->
    <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="item.tenantId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分拨类型" prop="deliverType">
          <el-select
            v-model="distribution.deliverType"
            placeholder="请选择分拨类型"
            size="mini"
            style="width: 90%"
          >
            <el-option
              v-for="(item, index) in distributionlist"
              :label="item.dictValue"
              :value="item.dictKey"
              :key="item.dictKey"
            ></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="handleSubmit" 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,
  allocate,
  tenant,
  simdeliver,
  channelfillData,
} from "@/api/communication/basiccard";
import { mapGetters } from "vuex";
import { getToken } from "@/util/auth";
export default {
  data() {
    var starts = (rule, value, callback) => {
      if (
        this.distribution.numEnd == null ||
        this.distribution.numStart == null
      ) {
        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 {
        callback();
      }
    };
    return {
      form: {},
      excelForm: {
        tenantId: "",
        isCovered: 0,
      },
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "通道名称",
            prop: "tenantId",
            type: "select",
            span: 20,
            dicUrl: "/api/iot-sim/channel/fillData",
            props: {
              label: "name",
              value: "id",
            },
            rules: [
              {
                required: true,
                message: "请选择通道名称",
                trigger: "change",
              },
            ],
          },
          {
            label: "模板上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            disabled: true,
            loadText: "模板上传中，请稍等",
            span: 24,
            propsHttp: {
              res: "data",
            },
            tip: "请上传 .xls,.xlsx 标准格式文件",
            action: "/api/iot-sim/simcard/import-simCard",
            rules: [
              {
                required: true,
                message: "请选择文件",
                trigger: "change",
              },
            ],
          },
          {
            label: "数据覆盖",
            prop: "isCovered",
            type: "switch",
            align: "center",
            width: 80,
            dicData: [
              {
                label: "否",
                value: 0,
              },
              {
                label: "是",
                value: 1,
              },
            ],
            value: 0,
            slot: true,
          },
          // {
          //   label: "模板下载",
          //   prop: "excelTemplate",
          //   formslot: true,
          //   span: 24,
          // },
        ],
      },
      distribution: {
        tenantId: "", //租户id
        deliverType: null, //分拨类型
        numStart: null, //开始号码
        numEnd: null, //结束号码
      }, //分拨
      distributionlist: [], //分拨类型下拉
      tenantlist: [], //租户下拉
      distrules: {
        tenantId: [
          { required: true, message: "请选择分拨租户", trigger: "change" },
        ],
        deliverType: [
          { required: true, message: "请选择分拨类型", trigger: "change" },
        ],
        numbers: [{ required: true, validator: starts, trigger: "blur" }],
      },
      channellist: [], //通道下拉
      ruleForm: {}, //导入
      dialogVisible: false, //分拨弹窗布尔
      query: {},
      selectionList: [],
      loading: false,
      excelBox: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      option: {
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        indexWidth: 70,
        addBtn: true,
        viewBtn: true,
        delBtn: true,
        excelBtn: false, //导出
        columnBtn: false,
        selection: false,
        dialogClickModal: false,
        dialogWidth: "60%",
        column: [
          {
            label: "通道名称",
            prop: "channelId",
            type: "select",
            dataType: "number",
            span: 12,
            labelWidth: 130,
            search: true,
            dicUrl: "/api/iot-sim/channel/fillData",
            props: {
              label: "name",
              value: "id",
            },

            rules: [
              {
                required: true,
                message: "请选择通道名称",
                trigger: "change",
              },
            ],
          },
          {
            label: "元流量池名称",
            prop: "flowPoolId",
            type: "select",
            dataType: "number",
            span: 12,
            labelWidth: 130,
            searchLabelWidth: 110,
            search: true,
            display: true,
            dicUrl: "/api/iot-sim/flowpool/fillData?isSource=" + 1,
            formatter: (val, value, label) => {
              if (value == -1) {
                return "-";
              } else {
                return `${label}`;
              }
            },
            props: {
              label: "name",
              value: "id",
            },
            rules: [
              {
                required: true,
                message: "请选择元流量池名称",
                trigger: "change",
              },
            ],
          },
          {
            label: "批次号",
            prop: "batchNum",
            span: 12,
            labelWidth: 130,
            search: 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,
            rules: [
              {
                required: true,
                message: "请输入imsi",
                trigger: "blur",
              },
            ],
          },
          {
            label: "msisdn",
            prop: "msisdn",
            span: 12,
            labelWidth: 130,
            search: true,
            rules: [
              {
                required: true,
                message: "请输入msisdn",
                trigger: "blur",
              },
            ],
          },
          {
            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,
            search: true,
            rules: [
              { required: true, message: "请选择卡类型", trigger: "change" },
            ],
          },
          {
            label: "是否出库",
            prop: "isDeliver",
            type: "select",
            dicUrl: "/api/iot-system/dict/dictionary?code=yes_no",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dataType: "number",
            span: 12,
            labelWidth: 130,
            width: 70,
            search: true,
            rules: [
              { required: true, message: "请选择是否出库", trigger: "change" },
            ],
          },
          {
            label: "沉默期最后时间",
            prop: "silentLastTime",
            span: 12,
            labelWidth: 130,
            type: "datetime",
            format: "yyyy-MM-dd hh:mm:ss",
            valueFormat: "yyyy-MM-dd hh:mm:ss",
            hide: true,
            rules: [
              {
                required: true,
                message: "请选择沉默期最后时间",
                trigger: "change",
              },
            ],
          },
          {
            label: "测试期最后时间",
            prop: "testLastTime",
            span: 12,
            labelWidth: 130,
            type: "datetime",
            format: "yyyy-MM-dd hh:mm:ss",
            valueFormat: "yyyy-MM-dd hh:mm:ss",
            hide: true,
            rules: [
              {
                required: true,
                message: "请选择测试期最后时间",
                trigger: "change",
              },
            ],
          },
        ],
      },
      data: [],
    };
  },
  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(",");
    },
  },
  created() {
    this.allocatelist(); //分拨列表
    this.tenantlists(); //租户下拉
  },
  watch: {
    "excelForm.tenantId"() {
      const column = this.findObject(this.excelOption.column, "excelFile");
      if (this.excelForm.tenantId != "") {
        if (process.env.NODE_ENV === "production") {
          column.disabled = false;
          column.action = `http://223.99.228.240:18081/iot-sim/simcard/import-simCard?channelId=${this.excelForm.tenantId}&isCovered=${this.excelForm.isCovered}`;
        } else {
          column.disabled = false;
          column.action = `/api/iot-sim/simcard/import-simCard?channelId=${this.excelForm.tenantId}&isCovered=${this.excelForm.isCovered}`;
        }
      } else {
        column.disabled = true;
      }
    },
    "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;
        }
      }
    },
  },
  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) {
      add(row).then(
        (res) => {
          if (res.data.data == true) {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!",
            });
            done();
          } else {
            this.$message({
              type: "error",
              message: "操作失败!",
            });
            done(); //关闭表单
            loading(); // 按钮停止加载
          }
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    //修改
    rowUpdate(row, index, done, loading) {
      update(row).then(
        (res) => {
          if (res.data.data == true) {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!",
            });
            done();
          } else {
            this.$message({
              type: "error",
              message: "操作失败!",
            });
            done(); //关闭表单
            loading(); // 按钮停止加载
          }
        },
        (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.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },
    //多选框
    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);
    },
    //批量出库
    delivery() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      } else {
        this.$message.error(this.ids);
        console.log(this.ids, typeof this.ids);
      }
    },
    //导出
    handleExport() {
      if (process.env.NODE_ENV === "production") {
        window.open(
          `http://223.99.228.240:18081/bd-core/tenant/dailybill/export-excel?${
            this.website.tokenHeader
          }=${getToken()}`
        );
      } else {
        window.open(
          `/api/iot-sim/simcard/export-simCard?${
            this.website.tokenHeader
          }=${getToken()}`
        );
      }
    },
    //导入弹窗开启
    handleImport() {
      this.excelBox = true;
    },
    //导入后
    uploadAfter(res, done, loading, column) {
      this.excelBox = false;
      this.refreshChange();
      done();
    },
    //下载模板
    handleTemplate() {
      window.open(
        `/api/iot-system/user/export-template?${
          this.website.tokenHeader
        }=${getToken()}`
      );
    },
    //分拨下拉框
    allocatelist() {
      allocate().then((res) => {
        if (res.data.code == 200) {
          this.distributionlist = res.data.data;
        }
      });
    },
    //租户下拉框
    tenantlists() {
      tenant().then((res) => {
        if (res.data.code == 200) {
          this.tenantlist = res.data.data;
        }
      });
    },
    //分拨弹窗开启
    handleAllocate() {
      this.dialogVisible = true;
    },
    //分拨弹窗关闭
    handleClose() {
      this.dialogVisible = false;
      this.$refs.distribution.resetFields();
    },
    //提交分拨
    handleSubmit() {
      this.$refs.distribution.validate((valid) => {
        if (valid) {
          simdeliver(this.distribution).then((res) => {
            if (res.data.data == "") {
              this.$message.success("操作成功");
              this.$refs.distribution.resetFields();
              this.dialogVisible = false;
            } else {
              const h = this.$createElement;
              this.$notify.error({
                title: "错误号码",
                message: h(
                  "i",
                  { style: "color: teal; word-break: break-all;" },
                  res.data.data
                ),
                duration: 0,
              });
              this.$refs.distribution.resetFields();
              this.dialogVisible = false;
            }
          });
        } else {
        }
      });
    },
    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;
        this.selectionClear();
      });
    },
  },
};
</script>

<style></style>
