<template>
  <view>
    <view class="content">
      <view class="card">
        <u-form labelPosition="left" :model="form" :rules="rules" ref="formRef" labelWidth="140px">
          <view v-for="(item, index) in list" :key="index">
            <view v-if="item.multiple === '1'" class="mt-10 multiple_btn">
              <u-button type="primary" size="mini" :customStyle="{width:'auto',margin:0}"
                        :text="'添加' + item.list[1].name" @click="fnAdd(index)"/>
            </view>
            <view v-for="(item1, index1) in item.list"
                  :key="index.toString() + index1.toString()"
                  :class="{'mt-10': item.multiple === '1' && index1 % 2 === 0,'multiple_form_item': item.multiple === '1'}">
              <u-form-item
                  :label="item1.name"
                  :prop="item1.key_name"
                  borderBottom
                  :required="item1.isRequired === '1'"
                  @click="fnSelect(item,item1)">
                <u-input v-model="form[item1.key_name]" border="none" readonly/>
                <u-icon name="arrow-right"/>
              </u-form-item>
              <u-icon name="close-circle-fill" color="#ff2929" size="20"
                      v-if="item.multiple === '1' && index1 !== 0 && index1 % 2 === 0"
                      :customStyle="{position: 'absolute',top:'-15rpx',right:'0'}"
                      @click="fnDelete(index,index1)"/>
            </view>
          </view>
        </u-form>
        <view class="mt-10">
          <u-button type="primary" text="下一步" @click="$u.debounce(fnSubmit, 1000,true)"/>
        </view>
      </view>
    </view>
    <u-picker :show="picker.show" :columns="picker.columns" keyName="NAME"
              :key="picker.currentColumnKey" @confirm="fnPickerConfirm" @cancel="fnPickerCancel"/>
  </view>
</template>

<script>
import {getUserList} from "@/api";
import {setPersonnelForm} from "@/utils/submitHomeworkProcess";

export default {
  data() {
    return {
      taskId: '',
      CORP_ID: '',
      TYPE: '',
      list: [],
      form: {},
      rules: {},
      picker: {
        show: false,
        columnsAll: {},
        columns: [],
        currentColumnKey: '',
        currentName: '',
        currentId: '',
      }
    }
  },
  onLoad() {
    const eventChannel = this.getOpenerEventChannel();
    eventChannel.on('nextNodes', (data) => {
      for (let i = 0; i < data.nextNodes.length; i++) {
        if (data.nextNodes[i].multiple === '1') {
          const guid = uni.$u.guid()
          for (let j = 0; j < data.nextNodes[i].list.length; j++) {
            // 把多选的后面随机拼接一个值，用于必填验证，提交数据的时候删除
            data.nextNodes[i].list[j].key_name = data.nextNodes[i].list[j].key_name + `&&${guid}`
            data.nextNodes[i].list[j].key_id = data.nextNodes[i].list[j].key_id + `&&${guid}`
          }
        }
      }
      this.list = data.nextNodes
      this.taskId = data.taskId
      this.CORP_ID = data.CORP_ID
      this.TYPE = data.TYPE
      this.fnInitFormAndRules()
    })
  },
  methods: {
    fnInitFormAndRules() {
      this.list.forEach((item) => {
        item.list.forEach((item1) => {
          // 将key_name和key_id作为form的key
          // 将key_name作为rules的key
          this.$set(this.form, item1.key_name, '')
          this.$set(this.form, item1.key_id, '')
          this.$set(this.rules, item1.key_name, [{
            required: item1.isRequired === '1',
            message: item1.name + '不能为空',
            trigger: ['blur', 'change'],
          }])
        })
      })
    },
    fnAdd(index) {
      const currentItem = this.list[index]
      // 克隆拿到当前的部门和人员
      const currentItemDepartment = uni.$u.deepClone(currentItem.list[0])
      const currentItemUser = uni.$u.deepClone(currentItem.list[1])
      // 重新生成key_id和key_name
      const guid = uni.$u.guid()
      currentItemDepartment.key_id = this.fnReSplicing(currentItemDepartment.key_id, guid)
      currentItemDepartment.key_name = this.fnReSplicing(currentItemDepartment.key_name, guid)
      currentItemUser.key_id = this.fnReSplicing(currentItemUser.key_id, guid)
      currentItemUser.key_name = this.fnReSplicing(currentItemUser.key_name, guid)
      // 添加到数组里
      currentItem.list.push(currentItemDepartment)
      currentItem.list.push(currentItemUser)
      // 将新生成的key_id和key_name添加到form和rules
      this.$set(this.form, currentItemDepartment.key_id, '')
      this.$set(this.form, currentItemDepartment.key_name, '')
      this.$set(this.form, currentItemUser.key_id, '')
      this.$set(this.form, currentItemUser.key_name, '')
      this.$set(this.rules, currentItemDepartment.key_name, [{
        required: currentItemDepartment.isRequired === '1',
        message: currentItemDepartment.name + '不能为空',
        trigger: ['blur', 'change'],
      }])
      this.$set(this.rules, currentItemUser.key_name, [{
        required: currentItemUser.isRequired === '1',
        message: currentItemUser.name + '不能为空',
        trigger: ['blur', 'change'],
      }])
    },
    fnReSplicing(value, guid) {
      return value.substring(0, value.indexOf('&&')) + `&&${guid}`
    },
    fnDelete(index, index1) {
      const departmentKeyId = this.list[index].list[index1].key_id
      const departmentKeyName = this.list[index].list[index1].key_name
      const userKeyId = this.list[index].list[index1 + 1].key_id
      const userKeyName = this.list[index].list[index1 + 1].key_name
      // 需要删除两遍，第一遍是部门，第二遍是人员
      this.list[index].list.splice(index1, 1)
      this.list[index].list.splice(index1, 1)
      // 在form和rules中删除
      delete this.form[departmentKeyId]
      delete this.form[departmentKeyName]
      delete this.form[userKeyId]
      delete this.form[userKeyName]
      delete this.rules[departmentKeyName]
      delete this.rules[userKeyName]
    },
    fnSelect({multiple}, {key_name, key_id, type, value}) {
      const key_value = multiple === '1' ? key_id.substring(key_id.indexOf('&&') + 2) : value
      if (type === '1') {
        this.fnSelectDepartment(key_name, key_id, key_value)
        return
      }
      if (type === '0') {
        this.fnSelectUser(key_name, key_id, key_value)
      }
    },
    fnSelectDepartment(key_name, key_id, value) {
      const guid = key_name.substring(key_name.indexOf('&&'))
      uni.navigateTo({
        url: `/pages/eight_assignments/select_department?CORP_ID=${this.CORP_ID}`,
        events: {
          confirm: (event) => {
            this.form[key_name] = event.DEPARTMENT_NAME
            this.form[key_id] = event.DEPARTMENT_ID
            this.form[value + '_USER_ID' + guid] = ''
            this.form[value + '_USER_NAME' + guid] = ''
            this.fnGetUserList(event, value)
          }
        },
      })
    },
    async fnGetUserList({DEPARTMENT_ID, TYPE}, value) {
      let resData = await getUserList({DEPARTMENT_ID, TYPE})
      for (let i = 0; i < resData.list.list.length; i++) {
        resData.list.list[i].NAME = resData.list.list[i].name || resData.list.list[i].NAME
        resData.list.list[i].USER_ID = resData.list.list[i].user_ID || resData.list.list[i].USER_ID
      }
      this.$set(this.picker.columnsAll, value, [resData.list.list])
    },
    fnSelectUser(key_name, key_id, value) {
      this.picker.currentName = key_name
      this.picker.currentId = key_id
      this.picker.currentColumnKey = value
      this.picker.columns = this.picker.columnsAll[this.picker.currentColumnKey]
      if (!this.picker.columnsAll[this.picker.currentColumnKey]) {
        uni.$u.toast('没有选择部门或当前部门没有人员')
        return
      }
      this.picker.show = true
    },
    fnPickerConfirm(event) {
      this.form[this.picker.currentId] = event.value[0].USER_ID
      this.form[this.picker.currentName] = event.value[0].NAME
      this.fnPickerCancel()
    },
    fnPickerCancel() {
      this.picker.show = false
    },
    async fnSubmit() {
      try {
        await this.$refs.formRef.validate()
        try {
          await setPersonnelForm({
            form: this.form,
            list: this.list,
            taskId: this.taskId,
            CORP_ID: this.CORP_ID,
            TYPE: this.TYPE
          })
        } catch {
        }
      } catch {
        uni.$u.toast('请补全必填项')
      }
    }
  },
}
</script>

<style scoped lang="scss">
.multiple_btn {
  display: flex;
  justify-content: end;
}

.multiple_form_item {
  position: relative;
  background-color: #f9f9f9;
  padding: 0 20rpx;
}
</style>
