<!--
 * @desc 任务配置-任务规则
 * @author linyuanjie
 * @date 2022/8/16
-->

<template>
  <div>
    <basic-container>
      <div class="rule-container">
        <!-- 平台显示左侧 -->
        <leftMentInfoEnterprise v-if="isAdmin" @select="select" />
        <!-- csm管理员 -->
        <leftMenu v-if="isCSM" @select="select" />
        <div class="right-area">
          <div class="r-title">
            任务类型配置
          </div>
          <div class="type-list" :style="{ height: maxHeight }">
            <div
              v-for="(item, index) in typeList"
              :key="index"
              class="select-list"
              :class="item.category"
              :style="{
                left: item.left,
                top: item.top
              }"
            >
              <el-checkbox
                :indeterminate="getAllSelectStatus(item)"
                v-model="item.enableFlag"
                @change="flag => allClick(flag, item)"
                ><span class="tit">{{ item.categoryName }}</span></el-checkbox
              >
              <div
                class="children-list"
                v-for="(iten, indey) in item.children"
                :key="indey"
              >
                <el-checkbox
                  v-model="iten.enableFlag"
                  @change="flag => childrenClick(flag, item)"
                  >{{ iten.taskTypeName }}</el-checkbox
                >
              </div>
            </div>
          </div>
          <div class="r-title">
            任务规则配置
          </div>
          <div v-if="Object.keys(formData).length !== 0" class="rule-form">
            <el-form
              ref="ruleFormRef"
              :model="formData"
              label-width="340px"
              label-position="left"
              size="mini"
              :inline="true"
            >
              <template>
                <div
                  v-for="(task, taskTitle, index) in formData"
                  :key="index"
                  class="mt10"
                  style="border-bottom: 1px solid #f0f2f5;"
                >
                  <div
                    class="f14 fwb"
                    style="width: 150px;
                display: inline-block;"
                  >
                    {{ dictMapping(taskTitle, "task_category") }}
                  </div>
                  <div v-for="(taskUnit, idx) in task" :key="idx">
                    <el-checkbox
                      v-model="formData[taskTitle][idx].optFlag"
                      true-label="OK"
                      false-label="LOCKED"
                      class="mb10"
                      :class="{ ml150: idx > 0 }"
                    >
                      {{ dictMapping(taskUnit.subCategory, "task_sub_cate") }}
                    </el-checkbox>
                    <br />
                    <div
                      v-for="(ruleItem, ruleIdx) in taskUnit.rule"
                      :key="ruleIdx"
                      style="margin-left: 230px;"
                    >
                      <el-form-item
                        :key="taskUnit.subCategory + ruleItem.manual"
                        :label="ruleItem.manual + '：'"
                        :prop="
                          taskTitle +
                            '.' +
                            idx +
                            '.' +
                            'rule.' +
                            ruleIdx +
                            '.frequency'
                        "
                        :rules="getRules(taskTitle, idx)"
                      >
                        <div
                          v-for="(frequency, fIdx) in ruleItem.frequency"
                          :key="taskUnit.subCategory + ruleItem.manual + fIdx"
                        >
                          <el-input
                            v-model="
                              formData[taskTitle][idx].rule[ruleIdx].frequency[
                                fIdx
                              ].quantity
                            "
                            style="width: 100px;"
                            :class="{ mt8: fIdx > 0 }"
                          />
                          <span
                            v-if="frequency.separator === '/'"
                            class="ml8 mr8"
                          >
                            /
                          </span>
                          <span v-if="!frequency.separator" class="ml8 mr8">
                          </span>
                          <el-select
                            v-model="
                              formData[taskTitle][idx].rule[ruleIdx].frequency[
                                fIdx
                              ].timeUnit
                            "
                            style="width: 100px;"
                          >
                            <el-option
                              v-for="item in timeUnitOption"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value"
                            />
                          </el-select>
                          <el-button
                            v-if="
                              ruleItem.multiple &&
                                fIdx === ruleItem.frequency.length - 1
                            "
                            class="ml10"
                            @click="addFrequency(taskTitle, idx, ruleIdx)"
                            >添加</el-button
                          >
                          <el-button
                            v-if="
                              ruleItem.multiple && ruleItem.frequency.length > 1
                            "
                            type="danger"
                            class="ml10"
                            @click="delFrequency(taskTitle, idx, ruleIdx, fIdx)"
                            >删除</el-button
                          >
                        </div>
                      </el-form-item>
                    </div>
                    <br />
                  </div>
                </div>
              </template>
            </el-form>
            <el-button
              class="save-btn"
              type="primary"
              :loading="buttonLoading"
              @click="saveFn"
              >保 存</el-button
            >
          </div>
        </div>
      </div>
    </basic-container>
  </div>
</template>

<script>
import {
  getEnterpriseLimit,
  saveEnterpriseLimit,
  listTaskType,
  updateTaskType
} from "@/api/taskrule";
import leftMentInfoEnterprise from "@/views/components/leftMentInfoEnterprise";
import { getDictType } from "@/api/common";
import leftMenu from "@/views/components/teamManagement/leftMenu";

export default {
  name: "index",
  data() {
    return {
      formData: {},
      typeList: [],
      typeIds: [],
      timeUnitOption: [],
      taskCategoryOption: [],
      taskSubCategoryOption: [],
      height: [0, 0, 0],
      maxHeight: 0,
      buttonLoading: false,
      deptId: this.$store.getters.userInfo.deptId,
      isAdmin: false,
      isCSM: false,
      id: ""
    };
  },
  created() {
    const userInfo = this.$store.getters.userInfo;
    if (userInfo.roles.includes(2) || userInfo.roles.includes(1)) {
      this.isAdmin = true;
    }
    if (userInfo.roles.includes(19)) {
      this.isCSM = true;
    }
  },
  computed: {
    getRules() {
      return (taskTitle, taskIdx) => {
        return [
          {
            required: this.formData[taskTitle][taskIdx].optFlag === "OK",
            trigger: "blur",
            validator: (rule, value, callback) => {
              this.formValidator(rule, value, taskTitle, taskIdx, callback);
            }
          }
        ];
      };
    }
  },
  methods: {
    saveFn() {
      this.getTaskTypeIds();
      this.$refs.ruleFormRef.validate(valid => {
        if (valid) {
          const params = [];
          for (const taskTitle in this.formData) {
            params.push(...this.formData[taskTitle]);
          }
          saveEnterpriseLimit(params).then(res => {
            if (res.data.code === 0) {
              this.$message.success("保存成功");
            } else {
              this.$message.error("保存失败");
            }
          });
          updateTaskType({
            taskTypeIds: this.typeIds,
            deptId: this.id
          }).then(res => {
            console.log("res", res);
          });
        } else {
          console.log("validate error");
          return false;
        }
      });
    },
    getTaskTypeIds() {
      let arr = [];
      for (let v of this.typeList) {
        for (let vv of v.children) {
          if (vv.enableFlag) {
            arr.push(vv.taskTypeId);
          }
        }
      }
      this.typeIds = arr;
    },
    formValidator(rule, value, taskTitle, taskIdx, callback) {
      const isChecked = this.formData[taskTitle][taskIdx].optFlag === "OK";
      const flag = value.every(ele => {
        return (
          ele.quantity !== "" &&
          ele.quantity !== undefined &&
          ele.quantity !== null &&
          !!ele.timeUnit
        );
      });
      if (isChecked && !flag) {
        callback(new Error("以上信息必填！"));
      } else {
        callback();
      }
    },
    addFrequency(taskTitle, taskUnitIdx, ruleIdx) {
      this.formData[taskTitle][taskUnitIdx].rule[ruleIdx].frequency.push({
        quantity: 1,
        separator: this.formData[taskTitle][taskUnitIdx].rule[ruleIdx]
          .frequency[0].separator,
        timeUnit: "DAY"
      });
    },
    delFrequency(taskTitle, taskUnitIdx, ruleIdx, frequencyIdx) {
      this.$confirm("确定删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.formData[taskTitle][taskUnitIdx].rule[ruleIdx].frequency.splice(
            frequencyIdx,
            1
          );
        })
        .catch(() => {});
    },
    async getEnterpriseLimitFn(deptId) {
      const res = await getEnterpriseLimit(deptId);
      this.formData = res.data.data;
    },
    async getListTaskType(deptId) {
      this.id = deptId;
      const res = await listTaskType(deptId);
      console.log("data", res.data.data);
      this.typeList = res.data.data;
    },
    // 获取时间单位字典
    getTimeUnit() {
      getDictType({ type: "time_unit" }).then(res => {
        this.timeUnitOption = res.data.data;
      });
    },
    // 获取任务分类字典
    getTaskCategory() {
      getDictType({ type: "task_category" }).then(res => {
        this.taskCategoryOption = res.data.data;
      });
    },
    // 获取任务子分类字典
    getTaskSubCategory() {
      getDictType({ type: "task_sub_cate" }).then(res => {
        this.taskSubCategoryOption = res.data.data;
      });
    },
    // 映射字典
    dictMapping(value, dictType) {
      const dictMap = {
        task_category: this.taskCategoryOption,
        task_sub_cate: this.taskSubCategoryOption
      };
      const dict = dictMap[dictType] || [];
      const filterItem = dict.filter(ele => ele.value === value);
      return filterItem.length ? filterItem[0].label : value;
    },
    // 左侧选中
    select(info) {
      console.log("info", info);
      this.formData = {};
      if (info) {
        this.typeList = [];
        this.getEnterpriseLimitFn(info.deptId);
        this.getListTaskType(info.deptId);
        let timerCalc = setInterval(() => {
          if (this.typeList.length) {
            clearInterval(timerCalc);
            this.calculateItemHeights();
          }
        }, 10);
      }
    },
    getAllSelectStatus(item) {
      let selectArr = [];
      item.children.forEach(iten => {
        if (iten.enableFlag) {
          selectArr.push(iten);
        }
      });
      let length = item.children.length;
      item.enableFlag = selectArr.length === length;
      return selectArr.length > 0 && selectArr.length < length;
    },
    allClick(flag, item) {
      item.children.forEach(item => (item.enableFlag = flag));
    },
    childrenClick(flag, item) {
      this.getAllSelectStatus(item);
    },
    calculateItemHeights() {
      this.height = [0, 0, 0];
      this.maxHeight = 0;
      this.typeList.forEach(item => {
        let className = "." + item.category;
        let element = document.querySelector(className);
        let min = Math.min(...this.height);
        let index = this.height.findIndex(item => item === min);
        item.height = element.clientHeight;
        let top = min;
        let leftMap = {
          0: "0%",
          1: "33%",
          2: "66%"
        };
        let left = leftMap[index];
        this.height[index] = min + element.clientHeight + 20;
        this.maxHeight = Math.max(...this.height) + 30 + "px";
        item.top = min + "px";
        item.left = left;
      });
      this.$forceUpdate();
    }
  },
  beforeMount() {
    this.getTaskCategory();
    this.getTaskSubCategory();
    this.getTimeUnit();
    // 企业
    if (this.deptId !== 0 && this.deptId !== 1) {
      this.getEnterpriseLimitFn(this.deptId);
      this.getListTaskType(this.deptId);
    }
  },
  mounted() {
    let timerCalc = setInterval(() => {
      if (this.typeList.length) {
        clearInterval(timerCalc);
        this.calculateItemHeights();
      }
    }, 10);
  },
  components: {
    leftMentInfoEnterprise,
    leftMenu
  }
};
</script>

<style lang="scss" scoped>
.rule-container {
  display: flex;
  background-color: #fff;
  .right-area {
    flex: 1;
    padding: 12px;
    .rule-form {
      padding: 16px;
      background-color: #fff;
      .save-btn {
        position: fixed;
        top: 150px;
        right: 50px;
        z-index: 1000;
      }
    }
  }
}
.r-title {
  font-size: 16px;
  color: #333;
  font-weight: 600;
  margin-bottom: 20px;
  padding-left: 10px;
}
.ml150 {
  margin-left: 150px;
}
.type-list {
  padding-left: 30px;
  position: relative;

  .select-list {
    position: absolute;
    width: calc(
      (100% - 10px) / 3
    ); // 这里的10px = (分布个数3-1)*间隙5px, 可以根据实际的分布个数和间隙区调整
    min-width: calc((100% - 10px) / 3); // 加入这两个后每个item的宽度就生效了
    max-width: calc((100% - 10px) / 3); // 加入这两个后每个item的宽度就生效了
    &:nth-child(3n) {
      // 去除第3n个的margin-right
      margin-right: 0;
    }
    .tit {
      font-size: 14px;
      font-size: #333;
      font-weight: 600;
    }
    .children-list {
      padding-left: 25px;
    }
  }
}
</style>
