<template>
  <div class="page-wrapper">
    <breadcrumb v-if="!multiPage" :breadcrumb-data="breadcrumbData" />
    <div class="page-container">
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="{ span: 7 }"
        :wrapper-col="{ span: 17 }"
      >
        <a-collapse
          v-model="activeKey"
          expand-icon-position="right"
          class="collapse-header-divide"
        >
          <a-collapse-panel key="a" :header="$t('BASE_INFO')">
            <a-row :gutter="24" type="flex">
              <a-col :span="8">
                <a-form-model-item
                  :label="$t('AUDIT_PROCESS_CODE')"
                  prop="checkProcessCode"
                  allow-clear
                >
                  <a-input
                    v-model="form.checkProcessCode"
                    :placeholder="`${$t('SYSTEM_DEFAULT_CODE')}${$t(
                      'DATE'
                    )}+${$t('NUMBER')}`"
                    @change="
                      form.checkProcessCode = form.checkProcessCode
                        .slice(0, 50)
                        .trim()
                    "
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  :label="$t('AUDIT_PROCESS_NAME')"
                  prop="checkProcessName"
                  allow-clear
                >
                  <a-input
                    v-model="form.checkProcessName"
                    :placeholder="$t('PLACEENTER')"
                    @change="
                      form.checkProcessName = form.checkProcessName
                        .slice(0, 50)
                        .trim()
                    "
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  :label="$t('PROCESS_TYPE')"
                  prop="checkProcessType"
                  allow-clear
                >
                  <a-select
                    v-model="form.checkProcessType"
                    :placeholder="$t('PLACEENTER')"
                  >
                    <a-select-option
                      v-for="(item, index) in typeList"
                      :key="index"
                      :value="item.value"
                      >{{ item.label }}</a-select-option
                    >
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  :label="$t('AUDIT_LEVELS')"
                  prop="checkProcessLevel"
                >
                  <a-input-number
                    v-model="form.checkProcessLevel"
                    :placeholder="$t('PLACEENTER')"
                    :min="1"
                    :max="6"
                    style="width: 100%"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="21">
              <div
                v-for="(item, index) in form.auditInfo"
                :key="index"
                class="audit-info pt-5 mb-2"
              >
                <a-col :span="8">
                  <a-form-model-item
                    :prop="'auditInfo.' + index + '.auditor'"
                    :rules="rules.auditor"
                  >
                    <span slot="label">
                      <span style="color: #f00">*</span>
                      <span>{{ $t("AUDITOR") }}</span>
                    </span>
                    <div style="display: flex">
                      <div style="position: relative; width: 100%">
                        <select-user
                          ref="selectUser"
                          v-model="item.auditor"
                          :multiple="true"
                          show-key="name"
                          row-key="id"
                          :default-selected-rows="auditRows[index].userRows"
                          :all-selected-keys="selectedUser"
                          :parent-params="{ index }"
                          @confirm="getReturnData"
                        />
                      </div>
                    </div>
                  </a-form-model-item>
                </a-col>
                <a-col :span="5">
                  <a-form-model-item
                    :label="$t('AUDIT_ORDER')"
                    :prop="'auditInfo.' + index + '.checkStatusId'"
                    :rules="rules.checkStatusId"
                    allow-clear
                  >
                    <a-select
                      v-model="item.checkStatusId"
                      :placeholder="$t('PLACEENTER')"
                      @change="
                        (e, option) => checkStatusChange(e, option, index)
                      "
                    >
                      <a-select-option
                        v-for="(list, idx) in checkStatusList"
                        :key="idx"
                        :value="list.id"
                        :disabled="
                          list.checkStatusNum <
                          (index > 0
                            ? form.auditInfo[index - 1].levelNum + 1
                            : 1)
                        "
                        >{{ list.checkStatusNum }}</a-select-option
                      >
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <a-col :span="5">
                  <a-form-model-item
                    :label="$t('ACCORDING_STATE')"
                    :prop="'auditInfo.' + index + '.checkStatusId'"
                    allow-clear
                  >
                    <a-select
                      v-model="item.checkStatusId"
                      :placeholder="$t('PLACEENTER')"
                      :disabled="true"
                    >
                      <a-select-option
                        v-for="(list, idx) in checkStatusList"
                        :key="idx"
                        :value="list.id"
                        >{{ list.checkStatusName }}</a-select-option
                      >
                    </a-select>
                  </a-form-model-item>
                </a-col>
              </div>
            </a-row>
          </a-collapse-panel>
        </a-collapse>
      </a-form-model>
    </div>
    <div class="page-bottom-op">
      <a-button type="primary" :loading="confirmLoading" @click="handleSave">
        <i class="iconfont icon-baocun"></i>
        {{ $t("SAVE") }}
      </a-button>
      <a-button @click="handleCancel">
        <i class="iconfont icon-quxiao"></i>
        {{ $t("CANCEL") }}
      </a-button>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { uniqBy, cloneDeep } from "lodash";
import ApiConstant from "@/api/ApiConstant";
// import FieldAuth from "@/components/FieldAuth";
import { fieldExReqDataFn } from "@/utils/fieldExtend";
import FieldExtendMixin from "@/mixins/fieldExtend";
import breadcrumb from "@/components/breadcrumb";
import SelectUser from "@/components/epms/SelectUser";

export default {
  components: {
    // FieldAuth,
    breadcrumb,
    SelectUser,
  },
  mixins: [FieldExtendMixin],
  data() {
    return {
      breadcrumbData: [
        {
          name: this.$t("AUDIT_CONFIG"),
          url: "/eam/basic_setting/audit_config",
        },
        { name: this.$t("ADD"), url: "" },
      ],
      activeKey: "a",
      confirmLoading: false,
      form: {
        checkProcessCode: "", // 签核流程编码
        checkProcessName: "", // 签核流程名称
        checkProcessType: "", // 流程类型
        checkProcessLevel: 1,
        auditInfo: [
          {
            auditor: "",
            checkStatusId: null,
            levelNum: 1,
          },
        ],
      },
      auditLevelList: [
        {
          checkUserIdList: [],
          checkStatusId: "",
          checkStatusNum: null,
        },
      ],
      auditRows: [{ userRows: [] }],
      typeList: [],
      checkStatusList: [],
    };
  },
  computed: {
    ...mapState("setting", ["multiPage"]),
    selectedUser() {
      let userIds = [];
      this.auditLevelList.forEach((list) => {
        userIds = [...userIds, ...list.checkUserIdList];
      });
      return userIds;
    },
    extandParams() {
      const {
        checkProcessCode,
        checkProcessName,
        checkProcessType,
        checkProcessLevel,
      } = this.form;
      const { auditLevelList } = this;
      let options = {};
      options = {
        checkProcessCode,
        checkProcessName,
        checkProcessType,
        checkProcessLevel,
        epmCheckProcessStepFormParamList: [...auditLevelList],
      };
      return options;
    },
    rules() {
      return {
        checkProcessCode: [
          {
            required: false,
            max: 50,
            message: () => this.$t("PLACEENTER") + 50 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
        checkProcessName: [
          {
            required: true,
            max: 50,
            message: () => this.$t("PLACEENTER") + 50 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
        checkProcessType: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        checkProcessLevel: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        auditor: [
          {
            validator: this.validateAudit,
            trigger: "blur",
          },
        ],
        checkStatusId: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
          {
            validator: this.validateNum,
            trigger: "blur",
          },
        ],
      };
    },
  },
  watch: {
    // 层级变化时
    "form.checkProcessLevel": function () {
      const { checkProcessLevel, auditInfo } = this.form;
      const nowLength = auditInfo.length;
      const needLength =
        Number(checkProcessLevel) > 6 ? 6 : Number(checkProcessLevel);
      const diff = needLength - nowLength;
      if (diff > 0) {
        const arr = Array(diff).fill("");
        arr.forEach((i) => {
          this.auditLevelList.push({
            checkUserIdList: [],
            checkStatusId: "",
            checkStatusNum: null,
          });
          const maxArr = this.form.auditInfo.map((item) => item.levelNum || 1);
          const maxNum = Math.max(...maxArr);
          this.form.auditInfo.push({
            auditor: "",
            checkStatusId: null,
            levelNum: maxNum + 1,
          });
          this.auditRows.push({
            userRows: [],
          });
        });
      }
      if (diff < 0) {
        this.auditLevelList.splice(diff);
        this.auditRows.splice(diff);
        this.form.auditInfo.splice(diff);
      }
    },
  },
  mounted() {
    // 数据详情
    const { id } = this.$route.query;
    if (id) {
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/epm/ebs/epm-check-process/get-by-id/${id}`
        )
        .then((res) => {
          this.auditRows = [];
          this.auditLevelList = [];
          this.form = { ...res.data?.data };
          const { epmCheckProcessStepBPOList } = this.form;
          const auditInfo = epmCheckProcessStepBPOList.map((item, index) => {
            const {
              epmCheckProcessStepUserBPOList,
              checkStatusId,
              checkStatusNum,
            } = item;
            const checkUserIdList = epmCheckProcessStepUserBPOList.map(
              (list) => list.checkUserId
            );
            const auditor = checkUserIdList.join();
            const userRows = epmCheckProcessStepUserBPOList.map((list) => {
              const { checkUserId, name, userName } = list;
              return {
                id: checkUserId,
                name,
                userName,
              };
            });
            this.$set(this.auditRows, index, {
              userRows,
            });
            this.auditLevelList.push({
              checkUserIdList,
              checkStatusId,
              checkStatusNum,
            });
            return {
              auditor,
              checkStatusId,
              levelNum: checkStatusNum,
            };
          });
          this.$set(this.form, "auditInfo", auditInfo);
          this.$set(this.form, "checkProcessCode", "");
        });
    }
    // 初始化数据
    this.init();
  },
  methods: {
    // 初始化数据
    init() {
      return Promise.all([
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:CHECK_PROCESS_TYPE`
        ), // 审核流程类型
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/epm/ebs/epm-check-status/get-by-type?checkStatusType=ASSETS`
        ), // 审核状态
      ]).then(([typeRes, checkStatusRes]) => {
        this.typeList = typeRes.data?.data;
        this.checkStatusList = checkStatusRes.data?.data;
        if (this.checkStatusList.length && !this.$route.query.id) {
          const { id, checkStatusNum } = this.checkStatusList[0];
          this.$set(this.form.auditInfo[0], "checkStatusId", id);
          this.$set(this.form.auditInfo[0], "levelNum", checkStatusNum);
          this.$set(this.auditLevelList[0], "checkStatusId", id);
          this.$set(this.auditLevelList[0], "checkStatusNum", checkStatusNum);
        }
      });
    },
    // 验证审核人员是否选择
    validateAudit(rule, value, callback) {
      const index = rule.field.split(".")[1];
      setTimeout(() => {
        if (!this.form.auditInfo[index].auditor) {
          callback(new Error(this.$t("PLACESELECT")));
        } else {
          callback();
        }
      }, 100);
    },
    // 验证审核顺序是否正确
    validateNum(rule, value, callback) {
      const checkNumArr = this.auditLevelList
        .filter((item) => item.checkStatusNum)
        .map((item) => item.checkStatusNum);
      const checkNumArrSort = cloneDeep(checkNumArr).sort();
      const newArr = Array.from(new Set(checkNumArr));
      const isA = checkNumArr.length !== newArr.length;
      const isB = checkNumArr.toString() !== checkNumArrSort.toString();
      setTimeout(() => {
        if (isA || isB) {
          callback(new Error(this.$t("NOT_CORRECT_ORDER")));
        } else {
          callback();
        }
      }, 100);
    },
    // 获取选择用户组件返回数据
    getReturnData(selectedKeys, selectedRows, parentParams) {
      const currentIndex = parentParams.index;
      this.auditLevelList[currentIndex].checkUserIdList = selectedKeys;
      this.$set(this.auditRows, currentIndex, {
        userRows: selectedRows,
      });
      const keys = [...selectedKeys].join();
      this.$set(this.form.auditInfo[currentIndex], "auditor", keys);
      this.$refs.ruleForm.validateField(`auditInfo.${currentIndex}.auditor`);
      this.$forceUpdate();
    },
    // 审批层级内审批顺序改变
    checkStatusChange(e, option, index) {
      const maxNum = option.key + 1;
      this.$set(this.form.auditInfo[index], "checkStatusId", e);
      this.$set(this.form.auditInfo[index], "levelNum", maxNum);
      this.$set(this.auditLevelList[index], "checkStatusId", e);
      this.$set(this.auditLevelList[index], "checkStatusNum", maxNum);
      const auditInfoLen = this.form.auditInfo.length;
      if (auditInfoLen > index + 1) {
        this.form.auditInfo.forEach((item, idx) => {
          if (idx > index) {
            this.$set(this.form.auditInfo[idx], "levelNum", maxNum + 1);
          }
        });
      }
      this.$refs.ruleForm.validateField(`auditInfo.${index}.checkStatusId`);
      this.$forceUpdate();
    },
    // 监听保存按钮点击事件
    handleSave() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          const params = this.extandParams;
          this.$axios
            .post(
              `${ApiConstant.PREFIX_CORE}/api/epm/ebs/epm-check-process`,
              params
            )
            .then(() => {
              this.confirmLoading = false;
              this.$message.success(this.$t("ADD_SUCCESS"));
              this.handleCancel();
            })
            .catch((e) => {
              this.confirmLoading = false;
            });
        }
      });
    },
    // 监听取消按钮点击事件
    handleCancel() {
      this.$store.dispatch("tagsView/jumpBeforeView", {
        to: {
          path: "/eam/basic_setting/audit_config",
        },
        vm: this,
      });
    },
    // 页面埋点
    handleFuncUseRate(data) {
      this.$axios
        .put(`${ApiConstant.PREFIX_CORE}/api/epm/eam/use`, data)
        .then(() => {});
    },
  },
};
</script>
<style lang="less" scoped>
@import "@/assets/css/fault_repair.less";
/deep/ .mega-design-business-table .mega-design-pro-table {
  padding: 0 !important;
  margin-bottom: 24px;
}
/deep/ .ant-form-item-label {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
/deep/ .ant-form-item-control .ant-form-item-children {
  .ant-input-disabled,
  .ant-input-number-disabled {
    background: #e1e6e9;
    color: #666;
  }
}
/deep/ .ant-select-disabled .ant-select-selection {
  background: #e1e6e9;
  color: #666;
}
.audit-info {
  width: 100%;
  height: 78px;
  background: #f4f7f9;
}
</style>
