<template>
  <a-modal
    v-model="visible"
    :title="title"
    destroy-on-close
    v-bind="{ width: 850 }"
    :mask-closable="false"
    @ok="save"
    @cancel="$emit('closed')"
  >
    <div :class="$style.warp">
      <sd-form ref="form" :key="updateKey" :init-values="values" :read-only="!editable">
        <template v-slot>
          <a-row v-for="(value, index) in values" :key="index">
            <a-col :span="24">
              <sd-form-item
                v-if="!((['groupUsers'].indexOf(value.name) > -1 && !unid) | ('id' === value.name))"
                :name="value.name"
                :input-props="                {
                  readOnly:
                    ['code'].indexOf(value.name) > -1 && unid && unid !== '' ? true : false,
                },
              "
              >
              </sd-form-item>
            </a-col>
          </a-row>
        </template>
      </sd-form>
    </div>
    <template slot="footer">
      <a-button
        type="white"
        @click="
          () => {
            visible = false
          }
        "
        >取消</a-button
      >
      <a-button v-if="editable" type="primary" @click="save">确定</a-button>
    </template>
  </a-modal>
</template>

<script>
import pickValues from '@/common/services/pick-values'
import sdUserPicker from '@/common/components/sd-user-picker.vue'
import { message } from 'ant-design-vue'
import TableActionTypes from '@/common/services/table-action-types'
import OrgService from './org-service'
import components from './_import-components/sd-org-role-import'

export default {
  name: 'SdOrgRole',
  metaInfo: {
    title: 'SdOrgRole',
  },
  components,
  props: {
    curParent: {
      type: Object,
      default: function() {
        return null
      },
    },
  },
  data() {
    return {
      title: '',
      editable: true,
      visible: false,
      unid: '',
      parentInfo: null,
      updateKey: 0,
      listDataUrl: `api/framework/v1/user-manager/roles/${this.unid}/users`,
      values: [
        {
          name: 'code',
          caption: '代码',
          dataType: 'string',
          required: true,
          attr: {
            defaultValue: 'G-1_',
            regex: /^(G-1_)/,
            regexMessage: '格式有误,必须以G-1_为前缀',
          },
        },
        {
          name: 'name',
          caption: '名称',
          required: true,
          dataType: 'string',
        },

        {
          name: 'index',
          caption: '优先级',
          dataType: 'number',
        },

        {
          name: 'description',
          caption: '描述',
          dataType: 'string',
        },
        {
          name: 'id',
          caption: '用户',

          dataType: 'string',
        },
      ],
      loadingMsg: null,
      columns: [
        {
          title: '账号',
          dataIndex: 'account',
          sdClickable: true,
          scopedSlots: {
            customRender: 'renderAccount',
          },
        },
        {
          title: '姓名',
          dataIndex: 'text',
          sdClickable: true,
        },
        {
          title: '机构',
          dataIndex: 'sortNumber',
          sdClickable: true,
        },
      ],
      actions: [
        {
          label: '新建',
          id: 'new',
          permission: null,
          // type: TableActionTypes.ex.create,
          callback: () => {
            this.actAddUsers()
          },
        },
        {
          label: '删除',
          id: 'delete',
          permission: null,
          type: TableActionTypes.batch,
          callback: (keys, rows) => {
            return this.deleteUsers(
              rows.map((item) => {
                return item.props.account
              })
            )
          },
        },
      ],
      curUsers: [],
    }
  },
  watch: {
    // unid: {
    //   handler(newVal, oldVal) {
    //     this.getDefaultValue()
    //   },
    //   immediate: true,
    // },
  },
  methods: {
    show(title, editable, unid) {
      this.title = title
      this.visible = true
      this.editable = editable
      this.unid = unid
      this.values.forEach((item) => {
        if (item.name === 'code') {
          if (unid) {
            item.attr.regex = ''
            item.attr.regexMessage = ''
          } else {
            item.attr.defaultValue = 'G' + this.curParent.id + '_'
            item.attr.regex = new RegExp('^(G' + this.curParent.id + '_)')
            item.attr.regexMessage = '格式有误,必须以G' + this.curParent.id + '_为前缀'
          }
        }
      })
      this.getDefaultValue()
    },
    processRes(resData) {
      this.curUsers = resData.map((item) => {
        return {
          code: item.userId,
          account: item.userAccont,
          title: item.userName,
        }
      })

      return {
        totalSize: resData.length,
        data: resData,
      }
    },
    processReq(req) {
      delete req.data.expressions
      delete req.data.columns
      req.params = req.data
      req.method = 'get'

      return req
    },
    actAddUsers() {
      pickValues(sdUserPicker, {
        disabledKeys: this.curUsers.map((item) => {
          return item.account
        }),
        hierarchical: false,
        required: true,
      }).then((res) => {
        if (!res) return

        this.addUsers(
          res.map((item) => {
            return item.code
          })
        )
      })
    },
    addUsers(ids) {
      this.loadingMsg = message.loading({
        key: this.msgKey,
        content: '处理中...',
        duration: 0,
      })
      return OrgService.roles
        .addUsers({
          id: this.unid,
          account: ids.join(','),
        })
        .then((res) => {
          if (res.status === 200) {
            message.success('处理成功')
            this.$refs.dataTable[0].refresh(true)
            this.$refs.dataTable[0].clearSelection(true)
          } else {
            message.error(res.data?.message || '处理失败')
          }
        })
        .catch(() => message.error('处理失败'))
        .finally(() => {
          this.loadingMsg?.()
        })
    },
    deleteUsers(ids) {
      this.loadingMsg = message.loading({
        key: this.msgKey,
        content: '处理中...',
        duration: 0,
      })
      return OrgService.roles
        .deleteUsers({
          id: this.unid,
          account: ids.join(','),
        })
        .then((res) => {
          if (res.status === 200) {
            message.success('处理成功')
            this.$refs.dataTable[0].refresh(true)
            this.$refs.dataTable[0].clearSelection(true)
          } else {
            message.error(res.data?.message || '处理失败')
          }
        })
        .catch(() => message.error('处理失败'))
        .finally(() => {
          this.loadingMsg?.()
        })
    },
    getDefaultValue() {
      if (this.unid) {
        this.loadingMsg = message.loading({
          key: this.msgKey,
          content: '处理中...',
          duration: 0,
        })
        OrgService.roles
          .getDoc({ id: this.unid })
          .then((res) => {
            const data = res.data
            this.values.forEach((item) => {
              if (['groupUsers'].indexOf(item.name) > -1) {
              } else {
                if (this.$refs.form) {
                  this.$refs.form.setFieldValue(item.name, data[item.name])
                } else {
                  item.value = data[item.name]
                }
              }
            })
          })
          .catch(() => message.error('加载失败'))
          .finally(() => {
            this.loadingMsg?.()
          })
      } else {
        if (this.$refs.form) {
          Promise.all([]).then(() => {
            this.values.forEach((item) => {
              if (['groupUsers'].indexOf(item.name) > -1) {
              } else {
                this.$refs.form.setFieldValue(item.name, undefined)
              }
            })
            this.updateKey++
          })
        }
      }
    },
    save() {
      return new Promise((resolve) => {
        this.$refs.form.validateFields().then((success) => {
          if (success) {
            const params = {
              props: {},
            }

            this.$refs.form.getBackendValues().forEach((item) => {
              params[item.name] = item.value
            })

            this.loadingMsg = message.loading({
              key: this.msgKey,
              content: '处理中...',
              duration: 0,
            })
            if (this.unid) {
            } else {
              params.id = 0
              params.parentId = this.curParent.id
              params.parentCode = this.curParent.name
            }
            return OrgService.roles
              .saveDoc(params)
              .then((res) => {
                if (res.status === 200) {
                  message.success('处理成功')
                  this.visible = false

                  this.$emit('feedback', true)
                  resolve(true)
                } else {
                  message.error(res.data?.message || '处理失败')
                }
              })
              .catch((res) => {
                message.error(res?.response?.data?.message || '处理失败')
              })
              .finally(() => {
                this.loadingMsg?.()
              })
          }
        })
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;

.warp {
  // 由于直接使用的a-col配合sd-form-item做的表单布局，label与内容区域需要显示在一行，特此处理
  :global(.ant-form-item .ant-form-item-label) {
    float: left;
    width: 25%;
  }
  :global(.ant-form-item .ant-form-item-control-wrapper) {
    float: left;
    width: 75%;
  }
  .no-label {
    :global(.ant-form-item .ant-form-item-control-wrapper) {
      float: left;
      width: 100%;
    }
  }

  :global(.ant-form-item) {
    margin-bottom: auto;
  }
}
</style>
