<template>
  <div class="feature-wrap">
    <v-tour name="queryListTour" :steps="steps" :options="tourOptions"></v-tour>
    <el-form class="select-container" label-width="100px" v-show="showSearch">
      <div class="search-vl">
        <el-form-item label="客户号:" label-width="60px">
          <el-input size="small" v-model="queryParams.custId" placeholder="请输入" clearable @clear="onSearch"
            @keyup.enter.native="onSearch"></el-input>
        </el-form-item>
        <el-form-item label="客户名:" label-width="60px">
          <el-input size="small" v-model="queryParams.custName" placeholder="请输入" clearable @clear="onSearch"
            @keyup.enter.native="onSearch"></el-input>
        </el-form-item>
        <el-form-item label="客户类型:">
          <el-select size="small" v-model="queryParams.custType" @change="onSearch" @clear="onSearch">
            <el-option v-for="item in clientTypeOptions" :key="item.value" :label="item.label" :value="item.value"
              :disabled="
                (detailInfoObj.opsDept === '0' && item.value === '2') ||
                (detailInfoObj.opsDept === '1' && item.value !== '2')
              ">
            </el-option>
          </el-select>
        </el-form-item>
      </div>
      <div class="search-operate">
        <el-button type="primary" size="small" class="common-search-btn" @click="onSearch">查询</el-button>
        <el-button size="small" type="plain" class="common-reset-btn" @click="onReset">重置</el-button>
      </div>
    </el-form>
    <section class="operate-area">
      <section class="vl">
        <svg-icon @click="backTo" class-name="icon-back" icon-class="icon-back" />

        <el-radio-group v-model="bindTab" @change="handlebindTabChange" size="medium" v-if="
          detailInfoObj.gridPattern === '3' &&
          detailInfoObj.isAddRelate &&
          !isCommonManager
        ">
          <el-radio-button label="1" value type="text">已分配</el-radio-button>
          <el-radio-button label="2" type="text">未分配</el-radio-button>
        </el-radio-group>
        <!-- <el-button type="primary" @click="distributeBatch" :disabled="multipleSelection.length === 0">批量分配</el-button>
      <el-button type="danger" @click="relieveBatch" :disabled="multipleSelection.length === 0">批量解除</el-button> -->
        <el-button type="plain" class="common-mini-btn" size="mini" style="
                    background-color: #4886f80f;
                    color: #4886f8;
                    border-color: #4886f8;
                  " plain @click="importOut">导出</el-button>
        <el-button type="plain" size="mini" class="common-mini-btn"
          v-if="detailInfoObj.gridPattern === '3' && detailInfoObj.isAddRelate" @click="onDistributed">手动指定</el-button>
      </section>
      <right-toolbar :showSearch.sync="showSearch" :columns="columns" @queryTable="getList"></right-toolbar>
    </section>
    <section class="table-wrap" id="tableWrap">
      <el-table v-loading="loading" ref="table1" :data="tableData" class="common-table-cnt"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <template v-for="item in columns">
          <el-table-column
            v-if="item.visible && item.isBtn"
            :prop="item.name"
            :label="item.label"
            :key="item.name"
            :width="item.width"
          >
            <template slot-scope="scope" v-if="item.name == 'custName' || item.name == 'custId' || item.name == 'custIdn'">
              <el-button type="text" @click="goDetail(scope.row)">{{
                scope.row[item.name]
              }}</el-button>
            </template>
          </el-table-column>
          <el-table-column v-if="item.visible && !item.isBtn && !item.isCustIdn" :prop="item.name" :label="item.label"
            :key="item.name" :width="item.width">


          </el-table-column>


        </template>
        <el-table-column label="移出状态" prop="transferStatus" key="transferStatus" v-if="detailInfoObj.gridPattern === '1'">
          <!-- <template slot-scope="scope">
            {{
              scope.row.status == "0"
                ? "审批中"
                : scope.row.status == "1"
                ? "通过"
                : scope.row.status == "2"
                ? "拒绝"
                : ""
            }}
          </template> -->
        </el-table-column>
        <el-table-column
          label="操作"
          v-if="
            detailInfoObj.gridPattern === '3' &&
            detailInfoObj.isUnbind &&
            bindTab === '1'
          "
          fixed="right"
        >
          <template #default="scope">
            <el-switch :prop="scope.row.bindFlag" v-model="scope.row.bindFlag" active-color="#2094ff"
              inactive-color="#666" @change="(e) => switchChange(e, scope.row)" />
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          v-if="
            detailInfoObj.gridPattern === '3' &&
            bindTab === '2' &&
            detailInfoObj.isAddRelate
          "
          fixed="right"
        >
          <template #default="scope">
            <el-button type="text" @click="() => onDistributed(scope.row)">
              手动指定
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" v-if="detailInfoObj.gridPattern === '1' && isCommonManager" fixed="right">
          <template #default="scope">
            <el-button type="text" @click="() => handleRemove(scope.row)" :disabled="!scope.row.transferFlag">
              移出
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </section>
    <pagination layout="total, prev, pager, next, sizes" v-show="total > 0" :total="total"
      :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" :pageSizes="pageSizes" @pagination="getList" />
    <modal-zd ref="modalZd" :gridId="detailInfoObj.gridId" titleName="分配负责人员" :perInfo="perInfo" @update-list="getList"
      @close-modal="closeModal" />
    <delete-modal ref="deleteModal" @deleteCompete="deleteCompete"></delete-modal>
    <unbindModal ref="unbindModal" :perInfo="perInfo" @update-list="getList" @close-modal="closeModal" />
    <el-dialog :visible.sync="dialogVisible" title="客户移出" :close-on-click-modal="false" :destroy-on-close="true"
      custom-class="myDialog" width="40%">
      <div>
        <el-form ref="pushform" :model="pushform" :rules="pushrules" label-width="100px" id="pushform">
          <el-row class="formItem">
            <el-col :span="24">
              <el-form-item label="移出到" prop="gridType">
                <el-radio-group v-model="pushform.gridType" width="100%">
                  <el-radio label="0">网格</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="formItem">
            <el-col :span="24">
              <el-form-item label="选择网格" prop="nextGridId">
                <el-select
                  v-model="pushform.nextGridId"
                  placeholder="请选择网格"
                  clearable
                  filterable
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in gridList"
                    :key="item.key"
                    :label="item.value"
                    :value="item.key"
                    :disabled="item.key == detailInfoObj.gridId"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="form-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  regionGridCustList,
  downloadFile,
  custManageOperate,
  upanddel,
  featureGridCustList,
  getVirCustManageData,
  custUnbind,
  custVirUnbind,
  getGridList,
  removeGridApi,
} from "@/api/grid/list/gridlist";
import ModalCnt from "./modal-cnt";
import modalZd from "./modal-zhiding.vue";
import unbindModal from "./unbind-modal.vue";
import { gridPatternMap } from "@/views/grid/create/list/constant-info";
import {
  commonCol,
  virtualCol,
  featureCol,
  appendColumns,
  regionCol,
  otherCol,
  roleMap,
} from "./constant-info";
import { custTypeMap } from "./../constant-info";
import { cloneDeep, isEmpty } from "lodash";
import { mapGetters } from "vuex";
import DeleteModal from "./delete-modal";
import { Message } from "element-ui";

export default {
  components: { ModalCnt, DeleteModal, modalZd, unbindModal },
  computed: {
    ...mapGetters(["roles"]),
    detailInfoObj() {
      return JSON.parse(sessionStorage.getItem("detailInfoObj"));
    },
    isTour() {
      return sessionStorage.getItem("isTour");
    },
    exportUrl() {
      return downloadFile;
    },
    exportParams() {
      return {
        custDistributeList: ["98"],
      };
    },
    isAdmin() {
      return this.roles.includes("admin") || this.roles.includes("headAdmin");
    },
    isBranchManage() {
      return this.roles.includes("branchAdmin");
    },
    isCommonManager() {
      return this.roles.includes("commonManager");
    },
  },
  data() {
    return {
      steps: [
        {
          target: "#tableWrap",
          content:
            '<div style="font-size:20px;line-height:25px">网格查询</div><br><span>支持查看网格中客户与客户经理的归属关系</span>',
          target: '#tableWrap',
          overlay: true,
          params: {
            placement: "auto",
            highlight: true,
            mask: true,
          },
        },
        {
          target: "#tableWrap",
          content:
            '<div style="font-size:20px;line-height:25px">网格查询</div><br><span>支持查看网格中客户与客户经理的归属关系</span>',
          overlay: true,
          params: {
            placement: "auto",
            highlight: true,
            mask: true,
          },
        },
        {
          target: "#tableWrap",
          content: "",
          overlay: true,
          before: () => {
            return this.$router.push({ path: "/grid/list" }).then(() => {
              return new Promise((resolve) => {
                const checkElement = () => {
                  sessionStorage.setItem("isTour", 5);
                  if (document.querySelector("#tableWrap")) {
                    resolve();

                  } else {
                    setTimeout(checkElement, 100);
                  }
                };
                checkElement();
              });
            });
          },
        },
      ],
      tourOptions: {
        highlight: true,
        labels: {
          buttonSkip: "跳过",
          buttonPrevious: "上一步",
          buttonNext: "下一步",
          buttonStop: "完成",
        },
        enabledButtons: {
          buttonSkip: true,
          buttonPrevious: true,
          buttonNext: true,
          buttonStop: true,
        },
        useKeyboardNavigation: true,
        startTime: 0,
        stopOnTargetNotFound: true,
        debug: false,
      },
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        custId: null,
        custName: null,
        distributeTag: null,
        custType: null,
      },
      tableData: [],
      multipleSelection: [],
      detailArr: [],
      columns: [],
      clientTypeOptions: [
        { value: "0", label: "个人" },
        { value: "1", label: "商户" },
        { value: "2", label: "企业" },
      ],
      dutyType: "",
      dutyTypeMap: {
        1: "责任网格",
        2: "竞争网格",
      },
      newStatus: false,
      perInfo: {},
      bindTab: "1",
      dialogVisible: false,
      pushform: {
        gridType: "0",
        nextGridId: "",
      },
      gridList: [],
      pushrules: {
        gridType: [{ required: true, message: "请选择移出类型" }],
        nextGridId: [{ required: true, message: "请选择网格" }],
      },
      currentRow: {},
      pageSizes: [10, 20, 30, 50, 100, 200, 500]
    };
  },
  mounted() {
    this.queryParams.custType = this.detailInfoObj.custType;
    this.getList();
    this.columns = this.getColumns();
    if (this.isTour == 3) {
      this.startTour();
    }
    this.getGridOption();
  },
  methods: {
    //获取下拉网格
    async getGridOption() {
      getGridList().then((res) => {
        if (res.code == 200) {
          this.gridList = res.data.map((item) => {
            return {
              key: item.gridId,
              value: item.gridName,
            };
          });
        }
      });
    },
    // 移出
    handleRemove(row) {
      this.currentRow = row;
      this.dialogVisible = true;
    },
    handleCancel() {
      this.pushform.nextGridId = "";
      this.currentRow = {};
      this.dialogVisible = false;
    },
    handleSave() {
      const { custId, custName, custType, secGridId } = this.currentRow;
      this.$refs.pushform.validate((valid) => {
        if (valid) {
          removeGridApi({
            custId,
            custName,
            custType,
            nextGridId: this.pushform.nextGridId,
            prevGridId: secGridId,
          }).then((res) => {
            if (res.code == 200) {
              Message.success("网格移出中,待审批");
              this.handleCancel();
              this.getList();
            }
          });
        } else {
          return false;
        }
      });
    },
    startTour() {
      this.$tours["queryListTour"].start(1);
      const tour = this.$tours["queryListTour"];
      tour.previousStep = function () {
        sessionStorage.setItem("isTour", "3");
        sessionStorage.setItem("isPrevious", "second");
        this.$router.push({ path: "/grid/list" });
      };
    },
    getColumns() {
      const newArr = cloneDeep(appendColumns);
      // newArr.splice(1,1)
      if (this.detailInfoObj.gridPattern === "3") {
        newArr.splice(4, 0, ...virtualCol);
        newArr.push(...otherCol);
        if (!this.detailInfoObj.isUnbind && this.bindTab === "1") {
          newArr.push({
            label: `分配状态`,
            visible: true,
            name: "bindFlagName",
          });
        }
        return newArr?.map((ot, oInd) => ({
          ...ot,
          key: oInd,
        }));
      } else if (this.detailInfoObj.gridPattern === "2") {
        newArr.splice(4, 0, ...featureCol);
        newArr.push(...otherCol);
        return newArr?.map((ot, oInd) => ({
          ...ot,
          key: oInd,
        }));
      } else {
        newArr.splice(4, 0, ...commonCol);
        newArr.push(...regionCol);
        newArr.splice(7, 0, {
          label: `所在行政区域`,
          visible: true,
          name: "regionName",
          width: "200",
          showOverflowTooltip: true,
        });
        return newArr?.map((ot, oInd) => ({
          ...ot,
          key: oInd,
        }));
      }
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      const params = {
        gridId: this.detailInfoObj.gridId,
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        distributeTag: this.newStatus ? "1" : "",
        custId: this.queryParams.custId,
        custName: this.queryParams.custName,
        custType: this.queryParams.custType,
      };
      if (this.detailInfoObj.gridPattern === "3") {
        if (this.bindTab === "2") {
          // 虚拟列表未分配
          params.isUnrelate = true;
        } else {
          params.isUnrelate = false;
        }
      }
      const API =
        this.detailInfoObj.gridPattern === "3"
          ? getVirCustManageData
          : this.detailInfoObj.gridPattern === "2"
            ? featureGridCustList
            : regionGridCustList;
      API(params)
        .then((res) => {
          this.tableData = res?.rows?.map((ot) => ({
            ...ot,
            gridPattern: gridPatternMap[ot.gridPattern],
            topGridDutyType: this.dutyTypeMap?.[ot.topGridDutyType] || "",
            secGridDutyType: this.dutyTypeMap?.[ot.secGridDutyType] || "",
            createRoleName: roleMap[ot.createRole],
            custPatternName:
              this.detailInfoObj.gridPattern !== "2"
                ? custTypeMap[ot.custType]
                : ot.custType,
            gridDutyTypeName: this.dutyTypeMap?.[ot.gridDutyType],
            bindFlag: !ot.unbindFlag,
            bindFlagName: !ot.unbindFlag ? "开启" : "关闭",
            custIdn:ot?.custIdn || ot?.custId?.slice(3)
          }));
          this.total = res.total;
        })
        .catch((err) => console.error(err))
        .finally(() => {
          setTimeout(() => {
            this.loading = false;
          }, 100);
        });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.detailArr = val?.map((ot) => ({
        custIds: ot.custId,
        custPatterns: ot.custPattern,
        belongBranchId: ot.belongBranchId,
        belongUserName: ot.belongUserName,
      }));
    },
    backTo() {
      // this.$router.go(-1)
      const { query } = this.$route;
      if (query.backUrl) {
        this.$router.replace({
          path: query.backUrl,
          query,
        });
      } else {
        this.$router.go(-1);
      }
    },
    onSearch() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    onReset() {
      this.queryParams.pageNum = 1;
      this.queryParams.distributeTag = "";
      this.queryParams.custId = "";
      this.queryParams.custName = "";
      this.getList();
    },
    distributeBatch() {
      this.$refs.modalCnt.onOpen();
    },
    relieveBatch() {
      const resultArr = this.detailArr.filter((ot) => !ot.belongUserName);
      if (!isEmpty(resultArr)) {
        return this.$message.warning(
          "所选列表存在归属客户经理为空时无法解除，请重新选择"
        );
      }
      const params = {};
      params.custIds = this.detailArr?.map((ot) => ot.custIds);
      params.custPatterns = this.detailArr?.map((ot) => ot.custPatterns);
      params.belongUserNames = [];
      params.belongUserIds = [];
      this.doDel(params);
    },
    importOut() {
      if (this.multipleSelection.length == 0) {
        this.$message.warning("请先指定客户导出");
        return;
      }
      const API =
        this.detailInfoObj.gridPattern === "3"
          ? "/grid/virtual/cust/export"
          : this.detailInfoObj.gridPattern === "2"
            ? "/draw/grid/export"
            : "/grid/region/cust/export";
      this.downloadPOST(
        `${API}`,
        this.multipleSelection,
        `${this.detailInfoObj.gridName}_${new Date().getTime()}.xlsx`,
        {},
        "post"
      );
      this.$refs.table1.clearSelection();
    },
    onAllocSearch() {
      this.newStatus = !this.newStatus;
      this.onSearch();
    },
    onDistributed(row) {
      this.dutyType = row.dutyType;
      this.detailArr = [
        {
          custIds: row.custId,
          custPatterns: row.custPattern,
          belongBranchId: row.belongBranchId,
        },
      ];
      this.perInfo = row;
      this.$refs.modalZd.onOpen();
    },
    gotoBindModal(row) {
      this.perInfo = row;
      this.$refs.unbindModal.onOpen();
    },
    async switchChange(e, row) {
      const API =
        this.detailInfoObj.gridPattern === "3"
          ? custVirUnbind
          : this.detailInfoObj.gridPattern === "2"
            ? custUnbind
            : "";
      const params =
        this.detailInfoObj.gridPattern === "3"
          ? {
            custId: row.custId,
            gridId: row.gridId,
            userName: row.userName,
            custType: row.custType,
          }
          : this.detailInfoObj.gridPattern === "2"
            ? {
              custId: row.custId,
              gridId: row.gridId,
              layerId: row.layerId,
              relateDeptId: row.relateDeptId,
              shapeId: row.shapeId,
              userName: row.userName,
              custType: row.custType,
            }
            : {};
      const res = await API(params);
      if (res.code === 200) {
        this.getList();
        this.$message.success(res.data);
      }
    },
    disDistributed() { },
    deleteCompete(row) {
      this.delRecord(row);
    },
    deleteClient(row) {
      if (this.isAdmin || (this.isBranchManage && this.dutyType === "1")) {
        const messageTips = this.isAdmin
          ? "提示: 解除后，客户仍属于该网格，但与所选的支行、网点、客户经理不再具有归属关系。"
          : "提示: 解除后，客户仍属于该网格，但与所选的网点、客户经理不再具有归属关系。";
        this.$confirm(messageTips, "是否确认解除", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.delRecord(row);
        });
      } else if (this.isBranchManage && this.dutyType === "2") {
        this.$refs.deleteModal.onOpen();
      }
    },
    async delRecord(row) {
      this.doDel({
        custIds: [row.custId],
        custPatterns: [row.custPattern],
        belongUserNames: [],
        belongUserIds: [],
      });
    },
    async doDel(params) {
      const res = await upanddel(params);
      if (res.code === 200) {
        this.$message.success("解除成功");
        if (this.dutyType === "2") {
          this.$refs.deleteModal.onPageChange(1);
        }
        this.onReset();
      } else {
        this.$message.error(res.msg);
      }
    },
    handlebindTabChange() {
      this.queryParams.pageNum = 1;
      this.columns = this.getColumns();
      this.getList();
    },
    closeModal() {
      this.perInfo = {};
    },
    goDetail(row) {
      if (row.custPatternName == "个人") {
        this.$router.push({
          path: "/360charts/indexcharts",
          query: {
            custId: row.custId,
          },
        });
      } else if (row.custPatternName == "商户") {
        this.$router.push({
          path: "/360charts/commercial/",
          query: {
            custId: row.custId,
          },
        });
      } else if (row.custPatternName == "企业") {
        this.$router.push({
          path: "/360charts/firm/",
          query: {
            custId: row.custId,
          },
        });
      }
    },
  },
};
</script>
<style  lang="scss" scoped>
.common-mini-btn {
  margin-left: 10px;
}

.feature-wrap {
  background-color: #ffffff;
  overflow: hidden;
  box-shadow: 0 3px 8px 0 #00000017;
  border-radius: 16px 16px 0 0;
  padding: 24px 30px;
  height: calc(100vh - 135px);
  overflow-y: auto;
}

.select-container {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;

  ::v-deep .search-vl {
    flex: 1;
    display: flex;
    align-items: center;
    gap: 24px;

    .el-form-item {
      flex-basis: calc((100% - 48px) / 3);
      margin-right: 0;
    }
  }

  ::v-deep .search-operate {
    width: 250px;
    margin-left: 10px;

    // padding: 0 30px;
    .el-form-item__content {
      display: flex;
      align-items: center;
      flex-wrap: nowrap;
      justify-content: space-between;
    }
  }

  ::v-deep .el-form-item {
    margin-bottom: 0;

    .el-form-item__label {
      color: #3d3d3d;
      font-size: 14px;
      font-weight: 400;
    }
  }

  &.is-more-query {
    flex-direction: column;

    .search-operate {
      width: 100%;
      text-align: right;
      display: flex;
      justify-content: flex-end;
      margin-top: 12px;
    }

    .search-vl {
      width: 100%;
      flex-wrap: wrap;

      .el-form-item {
        flex-basis: calc((100% - 48px) / 3);
      }
    }
  }
}

.batch-button {
  background-color: #409eff;
  color: white;
}

.distributed-button {
  border-radius: 0;
  border-top-left-radius: 20px;
  border-bottom-left-radius: 20px;
  border-top-right-radius: 20px;
  border-bottom-right-radius: 20px;
  background-color: #94c9ff;
  color: black;
}

.operate-area {
  margin-bottom: 16px;
  display: flex;
  align-items: flex-end;
  justify-content: space-between;

  .vl {}
}

::v-deep .pagination-container {
  .el-pagination__total {
    font-size: 12px;
    color: #222222;
  }

  .el-pager li {
    color: #222222;
    border: none;
    background-color: transparent;

    &.active {
      min-width: 31px;
      height: 31px;
      color: #4886f8;
      border-radius: 1.5px;
      border: 1px solid #4886f8;
      background-color: #ffffff;
    }
  }

  .btn-prev,
  .btn-next {
    background-color: transparent !important;
  }

  .el-pagination__sizes {
    margin: 0 10px 0 0;
  }

  .el-pagination__sizes .el-input__inner {
    font-size: 14px;
    color: #222222;
    border: none;
  }
}

.radius-btn {
  border-radius: 16px;
}

.icon-back {
  font-size: 20px;
  margin-right: 10px;
  cursor: pointer;
  vertical-align: middle;
}

::v-deep .myDialog {
  margin-top: 20vh !important;
}

.form-footer {
  text-align: right;
}
</style>
<style>
@import "../../../tour.css";
</style>
