<template>
  <div class="app-container">
    <el-form ref="processForm" :model="processForm" label-width="auto">
      <el-row>
        <el-form-item label="下一步处理方式">
          <el-radio-group v-model="processForm.changeState" @change="selectNextOperation">
            <el-radio v-for="node in nextNodeList" :key="'_node'+node.id" :label="node.nextState">{{ node.nextOperation }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-row>
      <div v-if="showDateTime">
        <el-row>
          <el-form-item label="完成时限">
            <el-date-picker
              v-model="processForm.limitedTime"
              :clearable="false"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择完成时限"/>
          </el-form-item>
        </el-row>
      </div>
      <div v-if="showSingleSelect">
        <el-row>
          <el-col :span="6">
            <el-form-item label="处理部门">
              <el-select key="muiltDept" v-model="processForm.dispatchDeptId" :loading="deptSelectLoading" filterable placeholder="请选择处理部门" @change="selectDisposalDept">
                <el-option v-for="item in disposalDeptList" :key="item.id" :label="item.simplename" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="交办处理人">
              <el-select key="singleUser" v-model="processForm.taskUserId" :loading="userSelectLoading" filterable placeholder="请选择处理人">
                <el-option v-for="item in normalUserList" :key="'single_'+item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div v-if="showMulitSelect">
        <el-row>
          <el-col :span="6">
            <el-form-item label="处理部门">
              <el-select key="muiltDept" v-model="selectedDept" :loading="deptSelectLoading" filterable placeholder="请选择处理部门" @change="selectDept" >
                <el-option v-for="item in deptList" :key="item.id" :label="item.simplename" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="会签处理人">
              <el-select key="MulitUser" v-model="selectedUserList" :loading="userSelectLoading" multiple filterable placeholder="请选择处理人" style="width:400px" @change="selectUser" >
                <el-option v-for="item in userList" :key="'mulit_'+item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="已选人员">
            <el-tag v-for="item in allUserList" :key="'user-'+item" closable @close="delSelect(item)">{{ userMap[item] && userMap[item].name }}</el-tag>
          </el-form-item>
        </el-row>
      </div>
      <el-row>
        <el-form-item label="反馈结果">
          <el-input v-model="processForm.remarks" type="textarea" maxlength="50" show-word-limit/>
        </el-form-item>
      </el-row>
      <el-row style="text-align: center;">
        <el-button class="submitBtn" type="primary" @click="onSubmit">提交</el-button>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import DeptSelect from '@/components/DeptSelect'
import { getDisposalDeptList, getUserList, getDeptList } from '@/api/callCase'
import { getNextNodeList, completeCaseTask } from '@/api/process'
export default {
  name: 'CaseProcess',
  components: { DeptSelect },
  props: {
    bizId: {
      type: String,
      default: ''
    },
    processId: {
      type: String,
      default: ''
    },
    taskId: {
      type: String,
      default: ''
    },
    caseState: {
      type: Number,
      default: null
    },
    limitedTime: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      processForm: { // 流程处理表单
        bizId: '', // 事件id（主键id）
        processId: '', // 流程ID
        currState: '', // 当前处理状态
        changeState: '', // 待变更状态
        remarks: '', // 备注
        dispatchDeptId: '', // 指派任务给某个组织机构
        taskUserId: '', // 任务指派人员,
        limitedTime: '' // 完成时限
      },
      nextNodeList: [], // 流程节点列表
      disposalDeptList: [], // 处置部门列表（交办用）
      normalUserList: [], // 处置人员列表（交办用）
      showSingleSelect: false, // 选择人员，单选
      showMulitSelect: false, // 选择人员，多选
      showDateTime: false, // 选择延期时间
      deptSelectLoading: false, // 处置部门选择框加载动画
      userSelectLoading: false, // 处理人选择框加载动画
      userQuery: {
        deptid: '', // 部门id （默认为当前用户部门）
        hasMine: '0', // 是否包含本人，1包含, 0不包含
        roleTips: '' // 角色标识，获取处置人员时传noraml
      },
      deptList: [], // 部门列表（会签用）
      userList: [], // 用户列表（会签用）
      userMap: {}, // 存储人员id：人员信息（会签用）
      deptMap: {}, // 存储部门id：部门下的已选人员（会签用）
      selectedDept: '', // 已选部门
      selectedUserList: [], // 下拉框多选用户列表
      allUserList: [] // 全部已选用户列表
    }
  },
  mounted() {
    this.processForm.bizId = this.bizId
    this.processForm.processId = this.processId
    this.processForm.currState = this.caseState

    this.fetchNextNodeList()
    this.fetchDisposalDeptList()
    this.fetchDeptList()
  },
  methods: {
    /**
     * 获取下级流转节点
     */
    fetchNextNodeList() {
      getNextNodeList(this.processForm.currState).then(response => {
        this.nextNodeList = response.data
      })
    },
    /**
     * 选择处理方式之后：
     * 如果下一步是交办，选择人员和部门（单选），清空相关信息
     * 如果下一步是会签，选择部门和人员（多选），清空相关信息
     * 否则，隐藏人员和部门，清空processForm中的dispatchDeptId和taskUserId
     */
    selectNextOperation(changeState) {
      this.showSingleSelect = false
      this.showMulitSelect = false
      this.showDateTime = false
      this.processForm.dispatchDeptId = ''
      this.processForm.taskUserId = ''
      this.processForm.limitedTime = ''

      this.normalUserList = []
      this.selectedDept = ''
      this.selectedUserList = []
      this.allUserList = []
      this.userMap = {}
      this.deptMap = {}
      // 交办
      if (changeState === 2) {
        this.showSingleSelect = true
      }
      // 会签
      if (changeState === 9) {
        this.showMulitSelect = true
        // console.log('select==>', this.selectedUserList)
      }
      if ((this.caseState === 6 || this.caseState === 33) && this.hasPerm('/changeLimitedTime')) {
        if (changeState !== 5) {
          this.processForm.limitedTime = this.limitedTime
          this.showDateTime = true
        }
      }
    },
    // 提交
    onSubmit() {
      console.log('submit')
      this.$confirm('确定提交案件处理吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 点击“确定”后的操作
        const isBuild = this.buildProcessForm()
        if (!isBuild) {
          return
        }
        this.$emit('loading')
        completeCaseTask(this.processForm).then(response => {
          console.log(response)
          if (response.code === 200) {
            this.$emit('submitSuccess')
          } else {
            this.$emit('submitError')
          }
        }).catch((res) => {
          this.$emit('submitError')
        })
      }).catch(() => {
        // 点击“取消”后的操作
      })
    },
    buildProcessForm() {
      if (!this.processForm.changeState) {
        this.$message.error('处理方式不能为空')
        return false
      }
      // 交办：传dispatchDeptId和taskUserId
      if (this.processForm.changeState === 2) {
        if (!this.processForm.dispatchDeptId) {
          this.$message.error('处理部门不能为空')
          return false
        }
        if (!this.processForm.taskUserId) {
          this.$message.error('处理人不能为空')
          return false
        }
      }
      // 会签：传countersigns,为对象列表，每个对象包含taskUserId和dispatchDeptId
      if (this.processForm.changeState === 9) {
        if (!this.allUserList || this.allUserList.length < 1) {
          this.$message.error('处理人不能为空')
          return false
        }
        // !!!!会签人员处理
        const counterSigns = this.allUserList.map(item => {
          const u = this.userMap[item]
          return {
            taskUserId: u.id,
            dispatchDeptId: u.deptId
          }
        })
        console.log('countersigns', counterSigns)
        this.processForm.countersigns = counterSigns
      }
      // 会签完成/未完成：传taskId
      if (this.processForm.currState === 9) {
        this.processForm.taskId = this.taskId
      }
      return true
    },
    /**
     * 获取处置单位列表（交办用）
     */
    fetchDisposalDeptList() {
      this.deptSelectLoading = true
      getDisposalDeptList().then(response => {
        this.disposalDeptList = response.data
        this.deptSelectLoading = false
      })
    },
    /**
     * 获取处置人员列表（交办用）
     */
    fetchNormalUserList() {
      this.userSelectLoading = true
      this.userQuery.roleTips = 'normal'
      getUserList(this.userQuery).then(response => {
        this.normalUserList = response.data
        this.userSelectLoading = false
      })
    },
    /**
     * 监听选择处置单位，获取处理人员（交办）
     */
    selectDisposalDept(val) {
      console.log('selectDisposalDept')
      this.normalUserList = []
      this.processForm.taskUserId = ''
      if (val) {
        this.userQuery.deptid = val
        this.fetchNormalUserList()
      }
    },
    /**
     * 获取部门列表（会签用）
     */
    fetchDeptList() {
      this.deptSelectLoading = true
      getDeptList().then(response => {
        this.deptList = response.data
        this.deptSelectLoading = false
      })
    },
    /**
     * 获取人员列表（会签用）
     */
    fetchUserList() {
      this.userQuery.roleTips = ''
      this.userSelectLoading = true
      getUserList(this.userQuery).then(response => {
        this.userList = response.data
        this.userList.forEach(item => {
          const iid = item.id
          if (this.allUserList.includes(iid)) {
            this.selectedUserList.push(iid)
          }
          this.userMap[iid] = item
        })
        console.log('userMap', this.userMap)
        this.userSelectLoading = false
      })
    },
    /**
     * 监听选择单位，获取人员列表（会签）
     */
    selectDept(val) {
      console.log('selectDept')
      this.userList = []
      this.selectedUserList = []
      if (val) {
        this.userQuery.deptid = val
        this.fetchUserList()
      }
    },
    /**
     * 选择人员（多选，会签）：
     * 将选择的人员放进deptMap中，然后遍历deptMap，将全部人员放入allUserList
     */
    selectUser(v) {
      this.deptMap[this.selectedDept] = v
      this.allUserList = Object.keys(this.deptMap).reduce((arr, item) => {
        return arr.concat(this.deptMap[item])
      }, [])
      console.log('tttt', this.allUserList, this.deptMap)
    },
    /**
     * 从数组中删除
     */
    delFromArr(arr, item) {
      arr.splice(arr.indexOf(item), 1)
    },
    /**
     * 从已选和全部已选中移除人员（会签）
     */
    delSelect(v) {
      this.delFromArr(this.allUserList, v)
      this.delFromArr(this.selectedUserList, v)
    }
  }
}
</script>

<style lang="scss" scoped>
.process-select {
  width: 200px;
}
</style>
