<template>
  <div class="directional-mutualExclusion">
    <Search :config="searchConfig" v-model="searchData">
      <el-button
        type="primary"
        icon="el-icon-search"
        size="small"
        @click="initData"
        >搜索</el-button
      >
      <el-button
        type="primary"
        icon="el-icon-plus"
        size="small"
        @click="addPage('add')"
        >新增</el-button
      >
      <el-button icon="el-icon-refresh" size="small" @click="initData('reset')"
        >刷新</el-button
      >
    </Search>
    <!-- table列表 -->
    <div class="directional-content">
      <el-table
        :data="tabList"
        style="width: 100%"
        :header-cell-style="{ 'background-color': '#E4E7ED', color: '#000' }"
      >
        <el-table-column prop="productName" label="产品名称    " align="center">
        </el-table-column>

        <el-table-column prop="spId" label="SPID" align="center">
        </el-table-column>
        <el-table-column
          prop="orderHuchiToName"
          label="订购互斥"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.orderHuchiToName || "--" }}
          </template>
        </el-table-column>
        <el-table-column prop="" label="关联退订" align="center">
          <template slot-scope="scope">
            {{ scope.row.relaUnsubToName || "--" }}
          </template>
        </el-table-column>
        <el-table-column prop="" label="审核状态" align="center">
          <template slot-scope="scope">
            {{ scope.row.auditStatus | auditStatusFilter }}
            <!-- <el-switch v-model="tabList[scope.$index]"></el-switch> -->
          </template>
        </el-table-column>
        <el-table-column prop="" label="状态" align="center">
          <template slot-scope="scope">
            {{ scope.row.status == 0 ? "生效" : "失效" }}
          </template>
        </el-table-column>
        <el-table-column prop="" label="创建时间" align="center">
          <template slot-scope="scope">
            {{ scope.row.createTime | formatDate }}
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="操作人" align="center">
        </el-table-column>
        <el-table-column prop="" label="操作" align="center" width="200px">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="mini"
              @click="editPage(scope.row.id, 'view')"
              >查看</el-button
            >
            <el-button
              :disabled="
                scope.row.auditStatus == 2 || scope.row.auditStatus == 1
                  ? false
                  : true
              "
              type="text"
              size="mini"
              @click="editPage(scope.row.id, 'edit')"
              >编辑</el-button
            >
            <el-button
              type="text"
              size="mini"
              @click="getVersionList(scope.row.auditSource)"
              >版本</el-button
            >
            <!-- <el-button
              type="text"
              size="mini"
              @click="deleteMutualExclusion(scope.row.id)"
              >删除</el-button
            > -->
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="directional-footer">
      <el-pagination
        :current-page="pagination.pageNum"
        :page-sizes="pagination.pageSizes"
        :page-size="pagination.pageSize"
        layout="total, sizes, pager"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 新增弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogShow"
      @before-close="beforeClose"
      @open="openDialog"
      width="500px"
    >
      <div class="dialog-content">
        <el-form
          :model="formData"
          ref="form"
          :rules="rules"
          label-position="right"
          label-width="80px"
        >
          <!-- 通用部分 -->
          <el-form-item label="产品名称" prop="productName">
            <!-- productNameChange -->
            <!-- <el-input v-model="formData.productName"></el-input> -->
            <el-select
              :disabled="dialogType == 'view' ? true : false"
              v-model="formData.productId"
              placeholder="请选择关联退订产品"
              filterable
              remote
              reserve-keyword
              :remote-method="getProdList"
              @change="productNameChange"
            >
              <el-option
                v-for="(item, i) in prodListSelect"
                :key="i"
                :label="item.productName"
                :value="item.id"
                :loading="loading"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="规则类型" prop="productRule">
            <el-select
              v-model="formData.productRule"
              placeholder=""
              :disabled="dialogType == 'view' ? true : false"
            >
              <el-option
                v-for="(item, i) in productRuleOption"
                :key="i"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="生效状态">
            <el-switch
              :disabled="dialogType == 'view' ? true : false"
              v-model="formData.status"
              active-text="生效"
              inactive-text="失效"
              :active-value="0"
              :inactive-value="1"
            ></el-switch>
          </el-form-item>
          <!-- 订购互斥，关联退订-->
          <template>
            <template v-if="formData.productRule == '1'">
              <el-form-item label="订购互斥" prop="orderHuchi">
                <div
                  class="flex-mutual"
                  v-for="(val, i) in mutualList"
                  :key="i"
                >
                  <i
                    v-if="dialogType != 'view'"
                    class="el-icon-circle-plus-outline mutual-icon"
                    @click="updateMutalList('add')"
                  ></i>
                  <el-select
                    :disabled="dialogType == 'view' ? true : false"
                    v-model="mutualList[i].id"
                    placeholder="请选择互斥订购产品"
                    filterable
                    remote
                    reserve-keyword
                    :remote-method="getProdList"
                  >
                    <el-option
                      v-for="(item, i) in prodListSelect"
                      :key="i"
                      :label="item.productName"
                      :value="item.id"
                      :loading="loading"
                    ></el-option>
                  </el-select>
                  <i
                    v-if="dialogType != 'view'"
                    class="el-icon-remove-outline mutual-icon"
                    @click="updateMutalList('delete', i)"
                  ></i>
                </div>
              </el-form-item>
            </template>

            <template v-if="formData.productRule == '2'">
              <el-form-item label="关联退订" prop="relaUnsub">
                <el-select
                  :disabled="dialogType == 'view' ? true : false"
                  v-model="formData.relaUnsub"
                  placeholder="请选择关联退订产品"
                  filterable
                  remote
                  reserve-keyword
                  :remote-method="getProdList"
                >
                  <el-option
                    v-for="(item, i) in prodListSelect"
                    :key="i"
                    :label="item.productName"
                    :value="item.id"
                    :loading="loading"
                  ></el-option>
                </el-select>
              </el-form-item>
            </template>
          </template>
          <!-- 查看模式 -->
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer" v-if="dialogType !== 'view'">
        <el-button @click="submit('draft')">保存草稿</el-button>
        <el-button type="primary" @click="showAuditDialog">提交审核</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="版本详情"
      :visible.sync="showVersion"
      @close="closeVersion"
      width="80vw"
    >
      <div style="overflow-y: scroll; height: 50vh">
        <el-table
          :data="auditVersionTable"
          style="width: 100%"
          :header-cell-style="{ 'background-color': '#E4E7ED', color: '#000' }"
        >
          <el-table-column
            prop="productName"
            label="产品名称    "
            align="center"
          >
          </el-table-column>

          <el-table-column prop="spId" label="SPID" align="center">
          </el-table-column>
          <el-table-column
            prop="orderHuchiToName"
            label="订购互斥"
            align="center"
          >
            <template slot-scope="scope">
              {{ scope.row.orderHuchiToName || "--" }}
            </template>
          </el-table-column>
          <el-table-column prop="" label="关联退订" align="center">
            <template slot-scope="scope">
              {{ scope.row.relaUnsubToName || "--" }}
            </template>
          </el-table-column>
          <el-table-column prop="" label="审核状态" align="center">
            <template slot-scope="scope">
              {{ scope.row.auditStatus | auditStatusFilter }}
              <!-- <el-switch v-model="tabList[scope.$index]"></el-switch> -->
            </template>
          </el-table-column>
          <el-table-column prop="" label="状态" align="center">
            <template slot-scope="scope">
              {{ scope.row.status == 0 ? "生效" : "失效" }}
            </template>
          </el-table-column>
          <el-table-column prop="" label="创建时间" align="center">
            <template slot-scope="scope">
              {{ scope.row.createTime | formatDate }}
            </template>
          </el-table-column>
          <el-table-column prop="creator" label="操作人" align="center">
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
    <el-dialog
      title="请选择产品互斥审核模板"
      :visible.sync="showAudit"
      width="350px"
    >
      <el-form :model="formData" ref="audit">
        <el-form-item
          label="审核模板"
          prop="auditTemplateId"
          :rules="[
            { required: true, message: '请选择审核模板', trigger: 'blur' },
          ]"
        >
          <el-select
            v-model="formData.auditTemplateId"
            placeholder="请选择审核模板"
          >
            <el-option
              v-for="(item, i) in auditList"
              :key="i"
              :label="item.templateName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showAudit = false">关闭</el-button>
        <el-button type="primary" @click="submit('FromData')">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import Search from "@/views/directional/components/Search.vue";
import {
  getMutualExclusionList,
  deleteMutualExclusion,
  addMutualExclusion,
  updateMutualExclusion,
  getMutualExclusionDetail,
  productList,
  saveToDraft,
  huchiSubmit,
  getAuditTemplate,
  getHistoryVersion,
} from "@/api/directional";
import { Message } from "element-ui";
import { mapState } from "vuex";
import { parseTime } from "@/utils";
// 编辑已添加的数据，需要记录 huchiId(现在未添加)
export default {
  name: "DirectionalList",
  components: {
    Search,
  },
  computed: {
    ...mapState({
      userName: (state) => state.user.name,
    }),
  },
  data() {
    return {
      // 搜索条件
      searchData: {
        productName: "",
        spId: "",
        relaUnsub: "",
        orderHuchi: "",
        productRule: "",
        createTime: "",
        orderHuchiToName: "",
        relaUnsubToName: "",
        auditStatus: "",
        status: "",
      },
      initVersion: null,
      searchConfig: [
        {
          title: "产品名称",
          key: "productName",
          type: "String",
          placeholder: "请输入名称",
        },
        {
          title: "SPID",
          key: "spId",
          type: "String",
          placeholder: "请输入SPID",
        },
        // 订购互斥

        {
          title: "订购互斥",
          key: "orderHuchiToName",
          type: "String",
          placeholder: "请输入订购互斥",
        },
        // 关联退订
        {
          title: "关联退订",
          key: "relaUnsubToName",
          type: "String",
          placeholder: "请输入关联退订",
        },
        // 产品规则
        {
          title: "产品规则",
          key: "productRule",
          type: "select",
          placeholder: "请输入产品规则",
          option: [
            { label: "全部", value: "" },
            { label: "订购互斥", value: "1" },
            { label: "关联退订", value: "2" },
          ],
        },
        // 生效状态
        {
          title: "生效状态",
          key: "status",
          type: "select",
          placeholder: "请输入产品规则",
          option: [
            { label: "全部", value: "" },
            { label: "生效", value: "0" },
            { label: "失效", value: "1" },
          ],
        },
        // 审核状态
        {
          title: "审核状态",
          key: "auditStatus",
          type: "select",
          placeholder: "请输入产品规则",
          // 0 待审核 1 审核通过 2 审核拒绝 3 二次审核中

          option: [
            { label: "全部", value: "" },
            { label: "待审核", value: "0" },
            { label: "审核通过", value: "1" },
            { label: "审核拒绝", value: "2" },
          ],
        },
        {
          title: "创建时间",
          key: "createTime",
          type: "date",
          placeholder: "请选择时间",
          config: {
            type: "daterange",
            startPlaceholder: "开始日期",
            endPlaceholder: "结束日期",
            format: "yyyy-MM-dd",
            rangeSeparator: "至",
          },
        },
      ],
      // 产品规则
      productRuleOption: [
        { label: "订购互斥", value: "1" },
        { label: "关联退订", value: "2" },
      ],
      //   分页
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        pageSizes: [10, 20, 50, 100, 300],
      },
      //   表单数据
      formData: {
        productId: "",
        productName: "",
        relaUnsub: "",
        orderHuchi: "",
        productRule: "1",
        spId: "",
        auditTemplateId: null,
        auditVersion: 0,
        auditStatus: 0,
      },
      // 列表
      tabList: [],
      //   表单验证
      rules: {
        productName: [
          { required: true, message: "请输入名称", trigger: "blur" },
        ],
        productRule: [
          { required: true, message: "请选择类型", trigger: "blur" },
        ],
        orderHuchi: [
          { required: true, message: "请选择订购互斥产品", trigger: "blur" },
        ],
        relaUnsub: [
          { required: true, message: "请选择关联退订产品", trigger: "blur" },
        ],
      },
      //   表单选定类型

      dialogTitle: "新增产品互斥关联规则",
      dialogType: "edit",
      dialogShow: false,
      loading: false,
      //  版本详情
      showVersion: false,
      tabListVersion: [],
      // 互斥产品列表
      mutualList: [{ id: "" }],
      // 产品列表
      prodListSelect: [],
      // 选择审核信息
      // 显示审核弹窗
      showAudit: false,
      // 查询审核列表
      auditList: [],
      auditVersionTable: [],
    };
  },
  methods: {
    openDialog() {
      this.resSetForm();
    },
    // 显示审核弹窗  //查询审核模板列表
    async showAuditDialog(type = "add") {
      this.showAudit = true;
      this.formData.orderHuchi = this.decodeOrderHuchi(2, this.mutualList);
      this.$refs["form"].validate(async (valid) => {
        if (!valid) return;
        // 初始化审核
        let { data, code } = await getAuditTemplate();
        this.auditList = data.records;
      });
    },
    // 初始化数据
    async initData(type) {
      if (type == "reset") {
        this.reset();
      }
      let {
        productName,
        spId,
        relaUnsub,
        orderHuchi,
        productRule,
        createTime,
        orderHuchiToName,
        relaUnsubToName,
        auditStatus,
        status,
      } = this.searchData;
      if (createTime == null || createTime.length == 0 || createTime == "") {
        createTime = ["", ""];
      }
      let { pageNum, pageSize } = this.pagination;
      let { data, code } = await getMutualExclusionList({
        pageNum,
        pageSize,
        productName,
        spId,
        relaUnsub,
        orderHuchi,
        productRule,
        orderHuchiToName,
        relaUnsubToName,
        beginTime: createTime[0],
        endTime: createTime[1],
        auditStatus,
        status,
      });
      if (code == 10000) {
        this.tabList = data.records;
        this.pagination.total = data.total;
      }
    },
    // 分页参数变化
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.initData();
    },
    handleCurrentChange(val) {
      this.pagination.pageNum = val;
      this.initData();
    },
    //需要打开什么弹窗
    async editPage(id, type) {
      this.getProdList("");
      this.getMutualExclusionDetail(id);
      this.dialogType = type;
      if (type == "edit") {
        this.dialogTitle = "编辑产品互斥关联规则";
      } else if (type == "view") {
        this.dialogTitle = "查看产品互斥关联规则";
      }
      this.dialogShow = true;
    },
    // 产品名称变化
    productNameChange(id) {
      let filterData = this.prodListSelect.find((item) => item.id == id);
      this.formData.productName = filterData.productName;
      this.formData.spId = filterData.spid;
    },
    // 提交表单数据，或者提交草稿
    submit(type) {
      this.formData.orderHuchi = this.decodeOrderHuchi(2, this.mutualList);
      // this.formData.creator = this.userName;
      this.$refs["form"].validate((valid) => {
        if (!valid) return;

        if (type == "draft") {
          this.formData.huchiId = this.formData.id;
          delete this.formData.createTime;
          delete this.formData.orderHuchiToName;
          delete this.formData.relaUnsubToName;
          delete this.formData.id;
          delete this.formData.creator;

          // this.formData.creator = this.userName;
          // this.formData.status = 0;
          if (this.formData.productRule == 1) {
            this.formData.relaUnsub = "";
          } else {
            this.formData.orderHuchi = "";
          }
          saveToDraft(this.formData).then((res) => {
            if (res.code == 10000) {
              Message({
                message: "保存草稿成功",
                type: "success",
              });
              this.dialogShow = false;
              this.resSetForm();
              this.$refs["form"].resetFields();
              this.initData();
            }
          });
        }
        if (type == "FromData") {
          this.$refs["audit"].validate(async (valid2) => {
            if (!valid2) return;
            delete this.formData.createTime;
            delete this.formData.orderHuchiToName;
            delete this.formData.relaUnsubToName;
            this.formData.auditVersion = this.initVersion + 1;
            huchiSubmit(this.formData).then((res) => {
              if (res.code == 10000) {
                Message({
                  message: "提交审核成功",
                  type: "success",
                });
                this.dialogShow = false;
                this.showAudit = false;
                this.resSetForm();
                this.$refs["form"].resetFields();
                this.initData();
              }
            });
          });
        }
        // if (valid) {
        //   this.dialogShow = false;
        //   this.$refs["form"].resetFields();
        //   this.initData();
        // } else {
        //   return false;
        // }
      });
      let orderHuchi = this.decodeOrderHuchi(2, this.mutualList);
    },
    // 修改数据
    async updateMutualExclusion(dataRow) {},
    // 删除互斥关联规则
    async deleteMutualExclusion(id) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let { data, code } = await deleteMutualExclusion(id);
          if (code == 10000) {
            Message({
              message: "删除成功",
              type: "success",
            });
            this.initData();
          }
        })
        .catch(() => {
          Message({
            message: "已取消删除",
            type: "info",
          });
        });
    },
    // 获取互斥关联规则详情
    async getMutualExclusionDetail(id) {
      let { data, code } = await getMutualExclusionDetail(id);
      // if (code == 10000) {

      this.formData = data;
      this.initVersion = data.auditVersion;
      this.mutualList = this.decodeOrderHuchi(1, data.orderHuchi);
      // }
    },
    async addPage(type) {
      if (type == "add") {
        this.getProdList("");
        this.dialogType = "add";
        this.dialogTitle = "新增产品互斥关联规则";
        this.dialogShow = true;
      } else if (type == "submit") {
        this.dialogType = "submit";
        this.dialogShow = false;
        // this.formData.creator = this.userName;
        // let res = await addMutualExclusion(this.formData);
      } else if ("draft") {
      }
    },
    // 重置表单
    resSetForm() {
      this.formData = {
        productName: "",
        relaUnsub: "",
        orderHuchi: "",
        productRule: "1",
        spId: "",
        auditTemplateId: null,
        auditVersion: 0,
        auditStatus: 0,
      };

      this.mutualList = [{ id: "" }];
    },
    reset() {
      // productName: "",
      //   spId: "",
      //   relaUnsub: "",
      //   orderHuchi: "",
      //   productRule: "",
      //   createTime: "",
      //   orderHuchiToName: "",
      //   relaUnsubToName: "",
      this.searchData.productName = "";
      this.searchData.spId = "";
      this.searchData.relaUnsub = "";
      this.searchData.orderHuchi = "";
      this.searchData.productRule = "";
      this.searchData.createTime = "";
      this.searchData.orderHuchiToName = "";
      this.searchData.relaUnsubToName = "";
      this.searchData.auditStatus = "";
      this.searchData.status = "";
    },
    // 解码订购互斥
    decodeOrderHuchi(type = 1, val) {
      // type 1解码 2编码
      if (type == 1) {
        let arr = val.split(",");
        let newArr = [];
        arr.forEach((item) => {
          newArr.push({ id: item });
        });
        return newArr;
      } else {
        let arr = [];
        val.forEach((item) => {
          arr.push(item.id);
        });
        return arr.join(",");
      }
    },
    // 关闭弹窗时需要做的事
    beforeClose() {
      this.resSetForm();
    },
    async getModuleList() {
      // let { data } = await getModuleList();
      // 获取审核列表
    },
    /**
     * @description: 版本详情
     * @param {type}
     * @return:
     *
     */
    //获取 版本详情
    async getVersionDetail(id) {
      // let { data } = await getVersionDetail({ id });
      // if (data.code == 10000) {
      //   this.tabListVersion = data.data;
      // }
    },
    // 版本详情列表
    async getVersionList(id) {
      this.showVersion = true;
      // 查找数据
      let { data } = await getHistoryVersion({ value: id });
      // if (data.code == 10000) {
      this.auditVersionTable = data;
      // }
      // this.getVersionList(id);
    },
    // 关闭版本详情
    closeVersion() {
      this.showVersion = false;
    },
    // 修改互斥产品列表
    updateMutalList(type, index) {
      if (this.mutualList.length == 1 && type == "delete") {
        Message({
          message: "至少存在一个互斥产品",
          type: "warning",
        });
        return;
      }
      if (type == "add") {
        this.mutualList.push({ id: "" });
      } else if (type == "delete") {
        this.mutualList.splice(index, 1);
      }
    },
    // 查询产品列表
    getProdList(query) {
      this.loading = true;
      productList({
        pageNum: 1,
        pageSize: 999,
        spName: query,
      }).then((res) => {
        this.loading = false;
        if (res.code == 10000) {
          this.prodListSelect = res.data.records;
        }
      });
    },
  },
  filters: {
    formatDate(time) {
      return parseTime(time, "{y}-{m}-{d} {h}:{i}:{s}");
    },
    // 版本详情 状态
    status(type) {
      // 0提交草稿箱,1待审核,2审核失败,3失效,4生效
      if (type == 0) {
        return "提交草稿箱";
      } else if (type == 1) {
        return "待审核";
      } else if (type == 2) {
        return "审核失败";
      } else if (type == 3) {
        return "失效";
      } else if (type == 4) {
        return "生效";
      }
    },

    // 产品关系
    classify(type) {
      if (type == "1") {
        return "订购互斥";
      } else if (type == "2") {
        return "关联退订";
      }
    },
    cpTypeFilter(val) {
      if (val == "0" || val == 0) {
        return "生效";
      } else {
        return "失效";
      }
    },
    auditStatusFilter(val) {
      // 0 待审核 1 审核通过 2 审核拒绝 3 二次审核中
      //  <span v-if="scope.row.auditStatus == 11">审核通过(已编辑)</span>
      // <span v-if="scope.row.auditStatus == 12">审核拒绝(已编辑)</span>
      if (val == "0" || val == 0) {
        return "待审核";
      } else if (val == "1" || val == 1) {
        return "审核通过";
      } else if (val == "2" || val == 2) {
        return "审核拒绝";
      } else if (val == "3" || val == 3) {
        return "二次审核中";
      } else if (val == "11" || val == 11) {
        return "审核通过(已编辑)";
      } else if (val == "12" || val == 12) {
        return "审核拒绝(已编辑)";
      }
    },
  },
  created() {
    this.initData();
    // this.getProdList("");
  },
};
</script>
<style scoped lang="scss">
.directional-mutualExclusion {
  padding: 20px;
  .directional-footer {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }
  .dialog-content {
    max-height: 50vh;
    overflow-y: auto;
  }
  .flex-mutual {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
  }
  .mutual-icon {
    margin: 0 15px;
    font-size: 24px;
    cursor: pointer;
  }
  .mutual-icon:nth-child(1) {
    margin-left: 0;
  }
}
</style>
