<template>
  <el-dialog
    :visible.sync="innerVisible"
    @close="handleClose"
    @open="initData"
    @closed="dataReset"
    append-to-body
    :close-on-click-modal="false"
    center
    title="审批节点配置"
    width="600px"
  >
    <el-form v-if="currentNode" label-width="200">
      <el-form-item label="启用">
        <el-switch
          v-model="currentNode.enable"
          disabled
        />
      </el-form-item>
      <el-form-item label="">
        <div class="handler-list">
          <el-tag
            v-for="(item,index) in currentNode.children"
            :key="`hl_${index}`"
            :type="childIndex === index ? '' : 'info'"
            closable
            @close="removeChild(index)"
            @click="childSelect(index)"
          >
            {{assigneeMap[item.assigneeType] || '未知'}}
          </el-tag>
          <el-button
            v-show="currentNode.enable"
            icon="el-icon-plus"
            size="mini"
            style="margin-bottom: 10px;"
            @click="addChild"
          />
        </div>
      </el-form-item>
      <el-form-item label="审批人">
        <el-radio-group
          v-model="currentNode.children[childIndex].assigneeType"
          :disabled="!currentNode.enable"
          @change="onAssigneeTypeChange"
        >
          <el-radio-button label="leader">组织管理员</el-radio-button>
          <el-radio-button label="user">指定人员</el-radio-button>
          <el-radio-button label="self">被考核人</el-radio-button>
          <el-radio-button label="post">岗位</el-radio-button>
          <el-radio-button label="deptLeader">部门负责人</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="">
        <template v-if="currentNode.children[childIndex].assigneeType === 'leader'">
          <el-select
            v-model="currentNode.children[childIndex].leaderLevel"
            placeholder="请选择管理员"
            :disabled="!currentNode.enable"
            filterable
            style="width: 300px;"
            key="leader"
            @change="onOrgManagerChange"
          >
            <el-option
              v-for="item in levelOptions"
              :key="`leader_${item.value}`"
              :label="item.label"
              :value="item.value"
              style="width: 300px;"
            />
          </el-select>
        </template>
        <template v-if="currentNode.children[childIndex].assigneeType === 'user'">
          <el-select
            v-model="userSelected"
            placeholder="请选择指定人员"
            multiple
            :disabled="!currentNode.enable"
            filterable
            style="width: 300px;"
            key="user"
            @change="onUserChange"
          >
            <el-option
              v-for="item in employees"
              :key="`user_${item.id}`"
              :label="item.name"
              :value="item.id"
              style="width: 300px;"
            />
          </el-select>
        </template>
        <template v-if="currentNode.children[childIndex].assigneeType === 'post'">
          <el-select
            v-model="postSelected"
            placeholder="请选择岗位"
            multiple
            :disabled="!currentNode.enable"
            filterable
            style="width: 300px;"
            key="post"
            @change="onPostChange"
          >
            <el-option
              v-for="item in postList"
              :key="`post_${item.id}`"
              :label="item.name"
              :value="item.id"
              style="width: 300px;"
            />
          </el-select>
        </template>
        <template v-if="currentNode.children[childIndex].assigneeType === 'deptLeader'">
          <el-select
            v-model="deptSelected"
            placeholder="请选择部门"
            multiple
            :disabled="!currentNode.enable"
            filterable
            style="width: 300px;"
            key="deptLeader"
            @change="onDeptChange"
          >
            <el-option
              v-for="item in deptList"
              :key="`deptLeader_${item.id}`"
              :label="item.name"
              :value="item.id"
              style="width: 300px;"
            />
          </el-select>
        </template>
      </el-form-item>
      <el-form-item label="多人时">
        <el-radio-group
          v-model="currentNode.children[childIndex].multipleType"
          :disabled="!currentNode.enable"
        >
          <el-radio-button label="or">任一人确认(或签)</el-radio-button>
          <el-radio-button label="parallel">按顺序确认(会签)</el-radio-button>
          <el-radio-button label="sequence">同时确认(会签)</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="允许">
        <el-checkbox-group
          v-model="currentNode.children[childIndex].allows"
          :disabled="!currentNode.enable"
        >
          <el-checkbox-button label="transfer">转交</el-checkbox-button>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-row type="flex" justify="end">
        <el-col align="end">
          <el-button
            type="primary"
            @click="onConfirm"
          >
            确认
          </el-button>
        </el-col>
      </el-row>
    </template>
  </el-dialog>
</template>


<script>
import Template from "../../examine/components/Template.vue";

export default {
  name: "PerReviewsSelectorOnly",
  components: {Template},
  props: {
    showVisible: {
      type: Boolean,
      default: false
    },
  },
  data(){
    return {
      userInfo: this.$userInfo(),
      currentNode: null,
      childIndex: null,
      innerVisible: this.showVisible,
      loading:false,
      employees:[],
      postList:[],
      deptList:[],
      userSelected:[],
      postSelected:[],
      deptSelected:[],
      assigneeMap:{
        leader:'组织管理员',
        user:'指定人员',
        self:'被考核人',
        post:'岗位',
        deptLeader:'部门负责人',
      },
      levelOptions: [
        {
          value: 1,
          label: '直接管理员'
        },
        {
          value: 2,
          label: '二级管理员'
        },
        {
          value: 3,
          label: '三级管理员'
        },
        {
          value: 4,
          label: '四级管理员'
        },
        {
          value: 5,
          label: '五级管理员'
        },
        {
          value: 6,
          label: '六级管理员'
        }
      ]
    }
  },
  computed:{
    employeeMap(){
      const map = {};
      this.employees.forEach(e => {
        if (!map[e.id]) map[e.id] = e.name;
      });
      return map;
    },
    postMap(){
      const map = {};
      this.postList.forEach(e => {
        if (!map[e.id]) map[e.id] = e.name;
      });
      return map;
    },
    deptMap(){
      const map = {};
      this.deptList.forEach(e => {
        if (!map[e.id]) map[e.id] = e.name;
      });
      return map;
    },
  },
  watch:{
    showVisible(val){
      this.innerVisible = val;
    },
  },
  methods: {
    defaultNode(){
      const node = JSON.parse("{\"id\":\"RS_1907236768800382982\",\"type\":\"reviews\",\"enable\":true,\"assigneeType\":\"leader\",\"leaderLevel\":1,\"assigneeIds\":[],\"multipleType\":\"or\",\"allows\":[\"transfer\"],\"weight\":0,\"children\":[{\"id\":\"R_1907236768800382983\",\"type\":\"review\",\"enable\":true,\"assigneeType\":\"leader\",\"leaderLevel\":1,\"assigneeIds\":[],\"multipleType\":\"or\",\"allows\":[\"transfer\"],\"weight\":0,\"children\":[]}]}");
      node.id = "RS_" + this.generalId();
      node.children.forEach((_,i) => {
        node.children[i].id = "R_" + this.generalId();
      });
      return node;
    },
    matchErrMsg(err){
      return err.toString().replace(/[(Error: )]/g,'');
    },
    handleClose(){
      this.$emit('update:showVisible',false);
    },
    dataReset(){
      this.currentNode = null;
      this.childIndex = null;
      this.userSelected = [];
      this.postSelected = [];
      this.deptSelected = [];
    },
    initData(){
      if (this.loading) return;
      this.dataReset();
      this.loading = true;

      let result = true;
      Promise.all([
        this.$axiosUser('get', '/api/pro/employee/index', {page:0,page_size:10,status:1}, 'v2'),
        this.$axiosUser('get','/org/post'),
        this.$axiosUser('get', `/org/departments/${this.userInfo.site_id}`)
      ])
        .then(([employeeRes,postRes,deptRes]) => {
          if (employeeRes.data.code !== 1) throw new Error(employeeRes.data.msg);
          if (postRes.data.code !== 1) throw new Error(postRes.data.message);
          if (deptRes.data.code !== 1) throw new Error(deptRes.data.message);

          this.employees = employeeRes.data.data.list
            .filter(e => e.account_id && e.account_id > 0)
            .map(e => {
              return {
                id:e.id,
                name:e.name,
              }
            });

          this.postList = postRes.data.data.map(item => {
            return {
              id: item.id,
              name: item.name,
            }
          });

          this.deptList = deptRes.data.data.list.map(item => {
            return {
              id: item.id,
              name: item.name,
            }
          });

          this.currentNode = this.defaultNode();

          this.childIndex = this.currentNode.children && this.currentNode.children.length > 0 ? 0 : null;

          if (this.childIndex !== null && !!this.currentNode.children[this.childIndex]){
            switch (this.currentNode.children[this.childIndex].assigneeType){
              case 'user':
                this.userSelected = [...this.currentNode.children[this.childIndex].assigneeIds];
                break;
              case 'post':
                this.postSelected = [...this.currentNode.children[this.childIndex].assigneeIds];
                break;
              case 'deptLeader':
                this.deptSelected = [...this.currentNode.children[this.childIndex].assigneeIds];
                break;
            }
          }
        })
        .catch(err => {
          this.$message.error(this.matchErrMsg(err));
          result = false;
        })
        .finally(() => {
          this.loading = false;
          if (!result) this.handleClose();
        })
    },
    generalId(){
      return Date.now() + Math.floor(Math.random() * 10000);
    },
    addChild(){
      let id = "R_" + this.generalId();
      this.currentNode.children.push({
        id:id,
        type:'review',
        enable:true,
        assigneeType:'leader',
        leaderLevel:1,
        assigneeIds:[],
        multipleType:'or',
        allows:['transfer'],
        weight:0,
        children:[],
      });
    },
    removeChild(index){
      if (this.currentNode.children.length <= 1 || !this.currentNode.children[index]) return;
      let selectChildId = this.currentNode.children[index].id;
      this.childIndex = 0;
      this.currentNode.children = this.currentNode.children.filter((_,i) => i !== index);
      if (selectChildId){
        this.currentNode.children.forEach((child,i) => {
          if (child.id === selectChildId) this.childIndex = i;
        })
      }
    },
    onAssigneeTypeChange(v){
      this.currentNode.children[this.childIndex].assigneeIds = [];
      this.currentNode.children[this.childIndex].leaderLevel = 1;
      this.userSelected = [];
      this.postSelected = [];
      this.deptSelected = [];
    },
    onOrgManagerChange(v){
      this.currentNode.children[this.childIndex].assigneeIds = [];
      this.currentNode.children[this.childIndex].leaderLevel = v;
      this.userSelected = [];
      this.postSelected = [];
      this.deptSelected = [];
    },
    onUserChange(v){
      this.currentNode.children[this.childIndex].assigneeIds = [...v];
      this.currentNode.children[this.childIndex].leaderLevel = 1;
      this.userSelected = v;
      this.postSelected = [];
      this.deptSelected = [];
    },
    onPostChange(v){
      this.currentNode.children[this.childIndex].assigneeIds = [...v];
      this.currentNode.children[this.childIndex].leaderLevel = 1;
      this.userSelected = [];
      this.postSelected = v;
      this.deptSelected = [];
    },
    onDeptChange(v){
      this.currentNode.children[this.childIndex].assigneeIds = [...v];
      this.currentNode.children[this.childIndex].leaderLevel = 1;
      this.userSelected = [];
      this.postSelected = [];
      this.deptSelected = v;
    },
    childSelect(index){
      if (!this.currentNode.children[index]) return;
      this.childIndex = index;
      this.userSelected = this.currentNode.children[this.childIndex].assigneeType === 'user' ? this.currentNode.children[this.childIndex].assigneeIds : [];
      this.postSelected = this.currentNode.children[this.childIndex].assigneeType === 'post' ? this.currentNode.children[this.childIndex].assigneeIds : [];
      this.deptSelected = this.currentNode.children[this.childIndex].assigneeType === 'deptLeader' ? this.currentNode.children[this.childIndex].assigneeIds : [];
    },
    onConfirm(){
      this.$emit('confirm',this.currentNode);
      this.handleClose();
    },
  }
}
</script>

<style scoped lang="scss">
.handler-list {
  width: 500px;
  margin: 0 auto 16px auto;
  border-radius: 6px;
  border: 1px solid #d7dae2;
  padding: 10px 0 0 10px;
  box-sizing: border-box;
  display: flex;
  flex-wrap: wrap;

  .el-tag {
    margin: 0 10px 10px 0;
    cursor: pointer;
  }
}

</style>
