<template>
  <div class="directional-draft">
    <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-refresh"
        size="small"
        @click="initData('reset')"
        >刷新</el-button
      >
    </Search>
    <div class="directional-content">
      <el-table
        :data="tabList"
        style="width: 100%"
        :header-cell-style="{ 'background-color': '#E4E7ED', color: '#000' }"
      >
        <el-table-column prop="id" label="草稿编号" align="center">
        </el-table-column>
        <el-table-column prop="productName" label="草稿名称" align="center">
        </el-table-column>
        <el-table-column prop="productRule" label="草稿类型" align="center">
          <template slot-scope="scope">
            {{ scope.row.productRule == "1" ? "订购互斥" : "关联退订" }}
          </template>
        </el-table-column>
        <!-- <el-table-column prop="" label="进度状态" align="center">
          <template slot-scope="scope">
            {{ "提交草稿箱" }}
          </template>
        </el-table-column> -->
        <el-table-column prop="creator" label="发起人" align="center">
        </el-table-column>

        <el-table-column
          prop="createTime"
          width="150px"
          label="发起时间"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.createTime | formatDate }}
          </template>
        </el-table-column>

        <el-table-column prop="" label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="showDialog(scope.row.id)"
              >修改</el-button
            >
            <el-button
              type="text"
              size="mini"
              @click="deleteDraft(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="修改草稿"
      :visible.sync="dialogShow"
      @before-close="beforeClose"
      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
              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="">
              <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
              v-model="formData.status"
              active-text="生效"
              inactive-text="失效"
              :active-value="0"
              :inactive-value="1"
            ></el-switch>
          </el-form-item>
          <!-- 订购互斥，关联退订-->

          <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
                  class="el-icon-circle-plus-outline mutual-icon"
                  @click="updateMutalList('add')"
                ></i>
                <el-select
                  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
                  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
                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>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="submit('draft')">保存草稿</el-button>
        <el-button type="primary" @click="showAuditDialog">提交审核</el-button>
      </span>
    </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 {
  huchiDraft,
  deleteDraft,
  updateMutualExclusion,
  productList,
  updateDraft,
  deleteDraftBox,
  getHuchiDraftDetail,
  huchiSubmit,
  getAuditTemplate,
} from "@/api/directional";
import { progressStatus } from "./editConfig";
import { Message } from "element-ui";
import { parseTime } from "@/utils/index.js";
import { mapState } from "vuex";
export default {
  name: "DirectionalList",
  components: {
    Search,
  },
  computed: {
    ...mapState({
      userName: (state) => state.user.name,
    }),
  },
  data() {
    return {
      showAudit: false,
      dialogShow: false,
      // 搜索条件
      searchData: {
        productName: "",
        createTime: "",
        status: null,
      },
      // 产品规则
      productRuleOption: [
        { label: "订购互斥", value: "1" },
        { label: "关联退订", value: "2" },
      ],
      formId: "",
      //   表单数据 (需要追寻互斥ID)
      formData: {
        productId: "",
        productName: "",
        relaUnsub: "",
        orderHuchi: "",
        productRule: "1",
        spId: "",
      },
      // 互斥产品列表
      mutualList: [{ id: "" }],
      // 产品列表
      prodListSelect: [],
      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" },
        ],
      },
      searchConfig: [
        {
          title: "草稿名称",
          key: "productName",
          type: "String",
          placeholder: "请输入草稿名称",
        },
        {
          title: "创建时间",
          key: "createTime",
          type: "date",
          placeholder: "请选择时间",
          config: {
            type: "daterange",
            startPlaceholder: "开始日期",
            endPlaceholder: "结束日期",
            valueFormat: "yyyy-MM-dd",
            rangeSeparator: "至",
          },
        },
        // {
        //   title: "进度状态",
        //   key: "status",
        //   type: "select",
        //   placeholder: "请选择状态",
        //   option: progressStatus,
        // },
      ],
      // 列表
      tabList: [],
      pagination: {
        pageNum: 1,
        pageSize: 20,
        total: 0,
        pageSizes: [20, 50, 100, 300],
      },
      initVersion: null,
      auditList: [],
    };
  },
  methods: {
    // 分页参数变化
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.initData();
    },
    handleCurrentChange(val) {
      this.pagination.pageNum = val;
      this.initData();
    },
    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.creator = this.userName;
          // this.formData.status = 0;
          if (this.formData.productRule == 1) {
            this.formData.relaUnsub = "";
          } else {
            this.formData.orderHuchi = "";
          }
          let id = this.formData.id;
          delete this.formData.id;
          delete this.formData.createTime;
          delete this.formData.orderHuchiToName;
          delete this.formData.relaUnsubToName;

          updateDraft(this.formData, id).then((res) => {
            if (res.code == 10000) {
              Message({
                message: "保存草稿成功",
                type: "success",
              });
              this.dialogShow = false;
              this.$refs["form"].resetFields();
              this.initData();
            }
          });
        }
        if (type == "FromData") {
          this.$refs["audit"].validate(async (valid2) => {
            if (!valid2) return;
            let id = this.formData.id;
            delete this.formData.id;
            delete this.formData.createTime;
            delete this.formData.orderHuchiToName;
            delete this.formData.relaUnsubToName;
            delete this.formData.creator;
            delete this.formData.huchiId;
            if (this.formData.huchiId == null) {
              delete this.formData.huchiId;
              delete this.formData.auditSource;
            } else {
              this.formData.auditVersion = this.initVersion + 1;
              this.formData.id = this.formData.huchiId
            }
            huchiSubmit(this.formData).then(async (res) => {
              if (res.code == 10000) {
                Message({
                  message: "提交审核成功",
                  type: "success",
                });
                this.dialogShow = false;
                this.showAudit = false;
                this.$refs["form"].resetFields();
                await deleteDraftBox(id);
                this.initData();
              }
            });
          });
        }
      });
    },
    // 修改数据
    async updateMutualExclusion(dataRow) {
      let { data } = await updateMutualExclusion(dataRow);
      if (data.code == 10000) {
        Message({
          message: "修改成功",
          type: "success",
        });
        this.initData();
      }
    },
    async showDialog(id) {
      this.dialogShow = true;
      this.getProdList();
      let { data } = await getHuchiDraftDetail(id);
      this.formData = data;
      this.initVersion = data.auditVersion;
      this.mutualList = this.decodeOrderHuchi(1, data.orderHuchi);
    },
    async initData(type) {
      if (type == "reset") {
        this.reset()
      }
      let { pageNum, pageSize } = this.pagination;
      let { productName, createTime, status } = this.searchData;
      if (createTime == null || createTime.length == 0 || createTime == "") {
        createTime = ["", ""];
      }
      let { data, code } = await huchiDraft({
        pageNum,
        pageSize,
        productName,
        status,
        beginTime: createTime[0],
        endTime: createTime[1],
      });
      if (code == 10000) {
        this.tabList = data.records;
        this.pagination.total = data.total;
      }
    },
    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;
      });
    },
    handlePage(page) {
      this.pagination = page;
      this.initData();
    },
    editPage(id) {
      this.$router.push({
        path: "/directional/directionalEdit",
        query: {
          id: id,
          type: "draft",
        },
      });
    },
    // 删除草稿
    deleteDraft(id) {
      this.$confirm("此操作将永久删除该草稿, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteDraftBox(id).then((res) => {
            if (res.code == 10000) {
              Message({
                message: "删除成功",
                type: "success",
              });
              this.initData();
            }
          });
        })
        .catch(() => {
          Message({
            message: "已取消删除",
            type: "info",
          });
        });
    },
    // 重置表单
    resSetForm() {
      this.formData = {
        productName: "",
        relaUnsubL: "",
        orderHuchi: "",
        productRule: "1",
        spId: "",
      };
     
      this.mutualList = [{ id: "" }];
    },
    reset(){
      this.searchData.createTime = "";
      this.searchData.productName = "";
      this.searchData.status = null;

    },
    // 解码订购互斥
    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(",");
      }
    },
    // 查询产品列表
    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;
        }
      });
    },
    // 关闭弹窗时需要做的事
    beforeClose() {
      this.resSetForm();
    },
  },
  filters: {
    formatDate(time) {
      return parseTime(time, "{y}-{m}-{d} {h}:{i}:{s}");
    },
    progressStatusFilter(status) {
      return progressStatus.find((item) => item.value == status)["label"];
    },
  },
  created() {
    this.initData();
  },
};
</script>
<style scoped lang="scss">
.directional-draft {
  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>
