<template>
  <a-modal
    v-model="visible"
    :title="title"
    destroy-on-close
    :mask-closable="false"
    :confirm-loading="confirmLoading"
    v-bind="{ width: 800 }"
    @ok="save"
    @cancel="visible = false"
  >
    <a-card>
      <sd-form ref="form" :init-values="values">
        <template v-slot="{ model }">
          <table>
            <tr>
              <sd-form-item-td
                name="fromUserId"
                :label-td-attrs="{
                  width: '100px',
                }"
              >
                <template>
                  <sd-user-picker
                    v-model="model.fromUserId"
                    :disabled-keys="
                      model.toUserId && model.toUserId[0] ? [model.toUserId[0].code] : []
                    "
                    :root-node="rootNode"
                    :single="true"
                    hierarchical
                    @change="getResources"
                  />
                </template>
              </sd-form-item-td>
            </tr>
            <tr>
              <sd-form-item-td name="toUserId">
                <template>
                  <sd-user-picker
                    v-model="model.toUserId"
                    :root-node="rootNode"
                    :disabled-keys="
                      model.fromUserId && model.fromUserId[0] ? [model.fromUserId[0].code] : []
                    "
                    hierarchical
                    :single="true"
                  />
                </template>
              </sd-form-item-td>
            </tr>
          </table>
        </template>
      </sd-form>
      <table v-if="showAction" :key="updateKey" :class="$style['act-table']">
        <thead>
          <tr>
            <th :class="$style['column-title']">交接项</th>
            <th :class="$style['column-act']">操作</th>
          </tr>
          <tr v-for="item in attrInfo" :key="item.id">
            <td>
              <template v-if="['roleInfo', 'groupInfo'].indexOf(item.id) > -1">
                <a-checkbox
                  v-if="item.value.length !== 0"
                  v-model="item.checked"
                  @change="
                    (evt) => {
                      setState(evt, item.id)
                      updateKey++
                    }
                  "
                >
                </a-checkbox>
              </template>
              {{ item.name }}({{
                ['roleInfo', 'groupInfo'].indexOf(item.id) > -1 ? item.value.length : item.value
              }}条)
              <a-tooltip v-if="item.id === 'processedNum'">
                <span slot="title">
                  已办包含已处理和已办结的数据
                </span>
                <a-icon type="question-circle-o" />
              </a-tooltip>
            </td>
            <td>
              <template v-if="['roleInfo', 'groupInfo'].indexOf(item.id) > -1">
                <a-checkbox-group
                  v-if="item.value.length !== 0"
                  v-model="item.checkedKeys"
                  :options="item.value"
                  @change="
                    (val) => {
                      setOneState(item.id, val)
                      updateKey++
                    }
                  "
                >
                </a-checkbox-group>
              </template>
              <template v-else>
                <a-checkbox
                  v-if="item.value !== 0"
                  v-model="item.checked"
                  :default-checked="true"
                  @change="
                    (evt) => {
                      updateKey++
                    }
                  "
                >
                </a-checkbox>
              </template>
            </td>
          </tr>
        </thead>
      </table>
    </a-card>
  </a-modal>
</template>

<script>
import { message } from 'ant-design-vue'
import HandoverService from './handover-service'
import components from './_import-components/sd-handover-action-import'

export default {
  name: 'SdHandoverAction',
  metaInfo: {
    title: 'SdHandoverAction',
  },
  components,
  data() {
    return {
      updateKey: 0,
      belongedOrg: '',
      confirmLoading: false,
      title: '',
      visible: false,
      showAction: false,
      loadingMsg: null,
      values: [
        {
          name: 'fromUserId',
          required: true,

          dataType: 'string',
          caption: '交接人',
        },
        {
          name: 'toUserId',
          required: true,
          dataType: 'string',
          caption: '承接人',
        },
      ],
      attrInfo: [
        {
          name: '待办',
          id: 'todoNum',
          key: 'toDo',
          value: 0,
        },
        {
          name: '待阅',
          id: 'toReadNum',
          key: 'toRead',
          value: 0,
        },
        {
          name: '已办',
          id: 'processedNum',
          key: 'processed',
          value: 0,
        },
        {
          name: '已阅',
          id: 'readNum',
          key: 'read',
          value: 0,
        },
        {
          name: '角色',
          id: 'roleInfo',
          key: 'roleIds',
          value: [],
        },
        {
          name: '用户组',
          id: 'groupInfo',
          key: 'userGroupIds',
          value: [],
        },
      ],
    }
  },
  computed: {
    rootNode() {
      if (this.belongedOrg) {
        return [{ code: this.belongedOrg.id, ...this.belongedOrg }]
      }
      return []
    },
  },
  methods: {
    setState(evt, id) {
      const attr = this.attrInfo.filter((item) => {
        return item.id === id
      })
      if (evt.target.checked) {
        attr[0].checkedKeys = attr[0].value.map((element) => {
          element.checked = evt.target.checked
          return element.value
        })
      } else {
        attr[0].checkedKeys = []
      }
    },
    setOneState(id, checkedValues) {
      const attr = this.attrInfo.filter((item) => {
        return item.id === id
      })
      attr[0].checkedKeys = checkedValues
      if (checkedValues.length !== attr[0].value.length) {
        attr[0].checked = false
      } else {
        attr[0].checked = true
      }
    },
    getResources() {
      if (this.$refs.form.getFieldValue('fromUserId').length === 0) {
        this.showAction = false
        return
      }
      const id = this.$refs.form.getFieldValue('fromUserId')[0].code

      this.loadingMsg = message.loading({
        key: this.msgKey,
        content: '处理中...',
        duration: 0,
      })
      HandoverService.getHandoverResources({ id })
        .then((res) => {
          const data = res.data
          this.attrInfo.forEach((item) => {
            if (['roleInfo', 'groupInfo'].indexOf(item.id) > -1) {
              if (data[item.id] === 0) {
                item.value = []
              } else {
                item.value = data[item.id].map((info) => {
                  return {
                    label: info.roleId ? info.roleName : info.groupName,
                    value: info.roleId ? info.roleId : info.groupId,
                    checked: true,
                    ...info,
                  }
                })
                item.checkedKeys = item.value.map((info) => {
                  return info.value
                })
                item.checked = true
              }
            } else {
              item.value = data[item.id]
              item.checked = true
            }
          })
          this.showAction = true
        })
        .catch(() => message.error('处理失败'))
        .finally(() => {
          this.loadingMsg?.()
        })
    },
    show(title) {
      this.title = title
      this.showAction = false
      this.visible = true
    },
    save() {
      return new Promise((resolve) => {
        this.$refs.form.validateFields().then((success) => {
          if (success) {
            const handoverItemsInfo = {}
            this.attrInfo.forEach((item) => {
              if (['roleInfo', 'groupInfo'].indexOf(item.id) > -1) {
                handoverItemsInfo[item.key] = item.checkedKeys.map((id) => {
                  return parseInt(id, 10)
                })
              } else {
                handoverItemsInfo[item.key] = item.checked ? 1 : 0
              }
            })
            this.loadingMsg = message.loading({
              key: this.msgKey,
              content: '处理中...',
              duration: 0,
            })
            this.confirmLoading = true
            HandoverService.saveDoc({
              fromUserAccount: this.$refs.form.getFieldValue('fromUserId')[0].code,
              toUserAccount: this.$refs.form.getFieldValue('toUserId')[0].code,
              handoverItemsInfo,
              belongedOrgId: this.belongedOrg?.id || '',
            })
              .then((res) => {
                if (res.status === 200) {
                  message.success('处理成功')
                  this.visible = false
                  this.$emit('feedback', true)
                } else {
                  message.error(res.data?.message || '处理失败')
                }
              })
              .catch(() => message.error('处理失败'))
              .finally(() => {
                this.loadingMsg?.()
                this.confirmLoading = false
                resolve()
              })
          }
        })
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.act-table {
  width: 100%;

  .column-title {
    width: 30%;
  }
  td {
    padding: 5px 0 5px 5px;
    border: 1px solid;
  }
}
</style>
