<template>
  <div class="select-users">
    <div v-if="showSelectUser">
      <el-radio
        v-model="newNextUser"
        v-for="(item, index) of newRadioList"
        v-show="newRadioList.length > 0 && !newMultiple && newPresetEdit != 0"
        :disabled="isCurrentNodeForbiddenChangeCandidate == 1"
        @change="cancelSelectUser(true)"
        :key="index"
        :label="item.id || item.showid"
        >{{ item.name ? item.name : item.showname }}</el-radio
      >
    </div>
    <el-checkbox-group
      :disabled="isCurrentNodeForbiddenChangeCandidate == 1"
      v-model="newNextUser"
      v-show="newRadioList.length > 0 && newMultiple && newPresetEdit != 0"
      @change="cancelSelectUser(true)"
    >
      <el-checkbox
        v-for="(item, index) of newRadioList"
        :key="index"
        :label="item.id || item.showid"
        >{{ item.name ? item.name : item.showname }}</el-checkbox
      >
    </el-checkbox-group>
    <!-- <el-select 
      v-model="newNextUser"
      :multiple="newMultiple"
      :class="isCustomUser ? 'es-select-user' : ''"
      filterable
      remote
      reserve-keyword
      placeholder="请输入办理人"
      :remote-method="remoteMethod"
      :loading="searchLoading"
      @change="changeSelectUser"
    >
      <el-option
        v-for="(item,index) in newOptions"
        :key="index"
        :label="item.name"
        :value="item.id"
      >
      </el-option>
    </el-select> -->
    <!-- class="select-user-icon el-button--primary" -->
    <div style="position: relative">
      <!-- <es-selector
        v-if="isChange"
        v-model="newSelectUserList"
        value-type="string"
        :types="types"
        :tabs="tabs"
        :title="title"
        :mix="mix"
        :multiple="newMultiple"
        @confirm="getSelectUser"
        @cancel="cancelSelectUser"
        :param="newParams"
      ></es-selector> -->
      <el-input v-if="disabled" :readonly="disabled" v-model="onlyName" />
      <es-selector
        v-else-if="!disabled && isChange"
        v-model="newSelectUserList"
        value-type="string"
        :types="types"
        :tabs="tabs"
        :title="title"
        reset
        :classify="classify"
        :collapse-tags="selectorTags"
        :mix="mix"
        :min="isUnionSeal ? 1 : 0"
        :disabled="!isCustomUser || isCurrentNodeForbiddenChangeCandidate == 1"
        :filterable="Boolean(isCustomUser && !isUnionSeal)"
        :class="
          isCustomUser &&
          isCurrentNodeForbiddenChangeCandidate == 0 &&
          !isUnionSeal
            ? ''
            : 'no-icon'
        "
        :select="isUnionSeal == false"
        :where="{ ...newWhere, info: classify ? '' : 'no' }"
        :multiple="newMultiple"
        @cancel="cancelSelectUser"
        :showTooltip="showTooltip"
        @change="getSelectUser"
        :param="{ ...newParams, info: classify ? '' : 'no' }"
        :disableds="disableds"
        ><i class="es-icon-yonghu"></i
      ></es-selector>
      <!-- es-icon-user -->
      <!-- :action="url" -->
      <!-- :where="{type:'user',a:'1'}" -->
      <!-- @confirm="getSelectUser" -->
    </div>
  </div>
</template>

<script>
import util from 'eoss-ui/src/utils/util.js';
import { handleInfo } from 'eoss-ui/src/config/api';
export default {
  name: 'SelectUser',
  props: {
    mix: {
      type: Boolean,
      default: false
    },
    tabs: {
      type: Object
    },
    showTooltip: {
      type: Boolean,
      default: true
    },
    isUnionSeal: {
      type: Boolean,
      default: false
    },
    nextUser: {
      default: () => []
    },
    disableds: {
      type: Array,
      default: () => []
    },
    radioList: {
      type: Array,
      default: () => []
    },
    multiple: {
      type: Boolean,
      default: false
    },
    selectorTags: {
      type: [Number, undefined],
      default: 2
    },
    isCustomUser: { type: Number, default: 1 },
    isCurrentNodeForbiddenChangeCandidate: { type: Number, default: 0 },
    options: {
      type: Array,
      default: () => []
    },
    selectUserList: {
      type: Array,
      default: () => []
    },
    types: {
      type: Array,
      default: () => ['employee']
    },
    params: {
      type: Object,
      default: () => {}
    },
    showUser: {
      type: Boolean,
      default: false
    },
    presetEdit: {
      type: Number,
      default: 0
    },
    title: {
      type: String,
      default: '下步处理对象'
    },
    onlyName: {
      type: String,
      default: ''
    },
    isDefSelectedObj: {
      type: Number,
      default: 0
    },
    where: {
      type: Object,
      default: () => {}
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      searchLoading: false,
      newNextUser: [],
      showSelectUser: true,
      classify: true,
      newOptions: [],
      newSelectUserList: [],
      url: handleInfo,
      newCheckboxList: [],
      newPresetEdit: 0,
      newMultiple: false,
      newIsDefSelectedObj: 0,
      isChange: true,
      newParams: {
        //  filid: 'all', //选择范围(my:本单位/ "" or all:全部)
        // selectmix: 'true1',
        // deptid: '' //指定部门(my:本部门)
      },
      newRadioList: []
    };
  },
  computed: {
    newWhere() {
      return {
        mid: `${
          JSON.parse(util.getStorage('mainConfig')).userModel.orgId
        }-org-1`,
        filid: JSON.parse(util.getStorage('mainConfig')).userModel.orgId,
        ...this.where
      };
    }
  },
  watch: {
    newPresetEdit(val) {
      this.isChange = false;
      setTimeout(() => (this.isChange = true), 0);
    },
    isDefSelectedObj: {
      handler(val) {
        this.newIsDefSelectedObj = val;
      },
      deep: true,
      immediate: true
    },
    params: {
      handler(val) {
        this.newParams = val;
      },
      deep: true,
      immediate: true
    },
    selectUserList: {
      handler(val) {
        this.newSelectUserList = val;
      },
      deep: true,
      immediate: true
    },
    nextUser: {
      handler(val) {
        this.newNextUser = val;
      },
      deep: true,
      immediate: true
    },
    radioList: {
      handler(val) {
        this.newRadioList = val;
      },
      deep: true,
      immediate: true
    },
    options: {
      handler(val) {
        this.newOptions = val;
      },
      deep: true,
      immediate: true
    },
    presetEdit: {
      handler(val) {
        this.newPresetEdit = val;
      },
      deep: true,
      immediate: true
    },
    multiple: {
      handler(val) {
        this.newMultiple = val;
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    console.log(this.nextUser,'nextUser')
    this.classify =
      util.getStorage('classify') != undefined
        ? util.getStorage('classify')
        : true;
  },

  methods: {
    changeInfo(data) {
      const {
        selectUserList,
        nextUser,
        radioList,
        options,
        multiple,
        presetEdit,
        isDefSelectedObj,
        params
      } = data;
      this.newSelectUserList = selectUserList;
      this.newNextUser = nextUser;
      this.newRadioList = radioList;
      this.newOptions = options;
      this.newMultiple = multiple;
      this.newParams = params;
      this.newPresetEdit = presetEdit;
      this.newIsDefSelectedObj = isDefSelectedObj;
    },
    remoteMethod(query) {
      if (query !== '') {
        this.searchLoading = true;
        util
          .ajax({
            url: handleInfo,
            params: { searchKey: query, query, type: 'user' }
          })
          .then((res) => {
            const { status, data } = res;
            this.searchLoading = false;
            if (status === 'success') {
              this.newOptions = data;
            }
          })
          .catch((err) => {
            this.searchLoading = false;
            if (err.message && err.message !== 'canceled') {
              this.$message.error(err.message);
            }
          });
      } else {
        this.newOptions = [];
      }
    },
    changeSelectUser(val) {
      this.newSelectUserList = [];
      if (this.newMultiple) {
        val.map((item) => {
          this.newOptions.map((items) => {
            if (item === items.id) {
              this.newSelectUserList.push({
                showname: items.name,
                showid: items.id
              });
            }
          });
        });
      } else {
        this.newOptions.map((item) => {
          if (item.id === val) {
            this.newSelectUserList.push({
              showname: item.name,
              showid: item.id
            });
          }
        });
      }
      this.$emit('change', {
        nextUser: this.newNextUser,
        options: this.newOptions
      });
    },
    getMixList() {
      let mixObj = this.newSelectUserList.reduce((obj, name) => {
        if (name.stype in obj) {
          obj[name.stype] += `,${name.showid}`;
        } else {
          obj[name.stype] = name.showid;
        }
        return obj;
      }, {});
      let mixArr = [];
      for (let key in mixObj) {
        mixArr.push(`${key}-${mixObj[key]}`);
      }
      return mixArr;
    },
    getSelectUser(val) {
      this.newOptions = [];
      let data = {};
      if (this.mix) data = this.getMixList();
      if (this.newMultiple) {
        this.newNextUser = [];
        this.newSelectUserList.map((item) => {
          if (this.mix) {
            this.newOptions.push({
              ...item,
              id: item.showid,
              name: util.getTypeName(item.stype) + item.showname
            });
          } else {
            this.newOptions.push({
              ...item,
              id: item.showid,
              name: item.showname
            });
          }
          this.newNextUser.push(item.showid);
        });
      } else {
        if (this.newSelectUserList.length > 0) {
          const { showid, showname } = this.newSelectUserList[0];
          if (val[0]) {
            this.newOptions.push({
              ...this.newSelectUserList[0],
              id: showid,
              name: showname
            });
            this.newNextUser = showid;
          } else {
            this.newOptions = [];
            this.newNextUser = '';
            this.showSelectUser = false;
            setTimeout(() => {
              this.showSelectUser = true;
            }, 0);
          }
        }else{
          this.newOptions = [];
            this.newNextUser = '';
             this.showSelectUser = false;
            setTimeout(() => {
              this.showSelectUser = true;
            }, 0);
        }
      }
      this.$emit('change', {
        nextUser: this.newNextUser,
        mixList: data,
        options: this.newOptions
      });
    },
    cancelSelectUser(type) {
      if (type) this.newOptions = this.newRadioList;
      let copy = JSON.stringify(this.newSelectUserList);
      let oldUserList = JSON.parse(copy);
      copy = [];
      this.newSelectUserList = [];
      let data = {};
      if (this.mix) data = this.getMixList();
      if (this.newMultiple) {
        this.newNextUser.map((item) => {
          //  if (this.mix) {
          //   this.newOptions.push({
          //     id: item.showid,
          //     ...item,
          //     name: util.getTypeName(item.stype) + item.showname
          //   });
          // } else {
          //   this.newOptions.push({...item, id: item.showid, name: item.showname });
          // }
          this.newOptions.map((items) => {
            oldUserList.map((val) => {
              if (items.showid != val.showid && val.showid == item) {
                this.newSelectUserList.push({
                  ...val
                });
              }
            });
            if (item === items.showid) {
              this.newSelectUserList.push({
                ...items
              });
            }
          });
        });
        var obj = {};
        this.newSelectUserList = this.newSelectUserList.reduce(function (
          item,
          next
        ) {
          obj[next.showid] ? '' : (obj[next.showid] = true && item.push(next));
          return item;
        },
        []);
      } else {
        this.newOptions.map((item) => {
          if (item.showid === this.newNextUser) {
            this.newSelectUserList.push({
              ...item
            });
          }
        });
      }
      this.$emit('change', {
        nextUser: this.newNextUser,
        mixList: data,
        options: this.newOptions
      });
    }
  }
};
</script>
