<template>
  <div :class="$style.warp">
    <sd-form ref="form" :key="updateKey" :init-values="values">
      <template v-slot="{ model }">
        <sd-form-item v-for="(value, index) in valuesMap" :key="index" :name="value.name">
          <template v-if="value.name === 'groupId'">
            <sd-value-picker v-model="model.groupId" single option-value="key" option-label="title">
              <template v-slot="scope">
                <sd-picker-source-tree :load-tree-data="onLoadTreeData" v-bind="scope" />
              </template>
            </sd-value-picker>
          </template>
          <template v-if="value.name === 'groupUsers'">
            <div>
              <div :class="$style.operationWrapper">
                <a-space>
                  <a-button class="editable-add-btn" @click="actAddUsers">
                    添加
                  </a-button>
                  <a-button
                    class="editable-delete-btn"
                    :disabled="selectedRowKeys.length === 0"
                    @click="deleteUsers"
                  >
                    删除
                  </a-button>
                </a-space>
              </div>
              <sd-table
                ref="dataTable"
                :columns="columns"
                :data-source="curUsers"
                :pagination="false"
                sortable
                row-key="userId"
                :row-selection="{
                  selectedRowKeys: selectedRowKeys,
                  onChange: selectedChange,
                }"
                @update:data-source="updateData"
              >
              </sd-table>
            </div>
          </template>
        </sd-form-item>
      </template>
    </sd-form>
  </div>
</template>

<script>
import pickValues from '@/common/services/pick-values'
import cloneDeep from 'lodash.clonedeep'
import sdUserPicker from '@/common/components/sd-user-picker.vue'
import { message } from 'ant-design-vue'
import OrgService from './org-service'
import components from './_import-components/sd-org-group-import'

export default {
  name: 'SdOrgGroup',
  metaInfo: {
    title: 'SdOrgGroup',
  },
  components,
  props: {
    unid: {
      type: String,
      default: function() {
        return null
      },
    },
    curNav: {
      type: Object,
      default: function() {
        return null
      },
    },
    curParent: {
      type: Object,
      default: function() {
        return null
      },
    },
  },
  data() {
    return {
      pagination: {},
      parentInfo: null,
      updateKey: 0,
      listDataUrl: 'api/framework/v1/usergroup-manager/userGroup/users/' + this.unid,
      values: [
        {
          name: 'code',
          caption: '代码',
          dataType: 'string',
          required: true,
        },
        {
          name: 'name',
          caption: '名称',
          required: true,
          dataType: 'string',
        },

        {
          name: 'groupId',
          caption: '所属机构',
          dataType: 'string',
          required: true,
        },

        {
          name: 'enabled',
          caption: '状态',
          dataType: 'selectlist',
          attr: {
            defaultValue: '1',
            selectListItem: [
              {
                value: '1',
                label: '启用',
              },
              {
                value: '0',
                label: '停用',
              },
            ],
          },
        },
        {
          name: 'sortNumber',
          caption: '排序序号',
          dataType: 'number',
        },
        {
          name: 'description',
          caption: '备注信息',
          dataType: 'string',
        },
        {
          name: 'groupUsers',
          caption: '用户',

          dataType: 'string',
        },
      ],
      loadingMsg: null,
      columns: [
        {
          title: '姓名',
          dataIndex: 'userName',
        },
        {
          title: '排序号',
          dataIndex: 'sortNumber',
        },
      ],
      curUsers: [],
      selectedRowKeys: [],
    }
  },
  computed: {
    valuesMap() {
      return this.values
    },
  },
  watch: {
    unid: {
      handler(newVal, oldVal) {
        this.getDefaultValue()
      },
      immediate: true,
    },
  },
  methods: {
    actAddUsers() {
      OrgService.getOrgRootByOrg({ group: this.$refs.form.getFieldValue('groupId')[0].key }).then(
        (resRoot) => {
          pickValues(sdUserPicker, {
            disabledKeys: this.curUsers.map((item) => {
              return item.account
            }),
            rootNode: [{ code: resRoot.data.id, name: resRoot.data.text }],
            hierarchical: false,
            required: true,
          }).then((res) => {
            if (!res) return
            const userCodes = res.map((item) => item.code)
            const options = {
              rootIds: [Number(resRoot.data.id)],
              hierarchical: false,
            }
            this.loadingMsg = message.loading({
              key: this.msgKey,
              content: '处理中...',
              duration: 0,
            })
            OrgService.queryUserByCode(userCodes, [], options)
              .then((data) => {
                this.addUsers(
                  data.map((item) => {
                    return {
                      ...item,
                      name: item.text,
                      id: item.id.replace('U', ''),
                    }
                  })
                )
              })
              .finally(() => {
                this.loadingMsg?.()
              })
          })
        }
      )
    },
    addUsers(users) {
      const data = users.map((item) => {
        return {
          userId: Number(item.id),
          userName: item.name,
        }
      })
      this.curUsers = this.curUsers.concat(data).map((item, index) => {
        return {
          ...item,
          sortNumber: index + 1,
        }
      })
    },
    deleteUsers() {
      const ids = this.selectedRowKeys
      this.curUsers = this.curUsers.filter((item) => {
        return ids.indexOf(item.userId) === -1
      })
      this.selectedRowKeys = []
    },
    getDefaultValue() {
      if (this.unid) {
        OrgService.group.getDoc({ id: this.unid }).then((res) => {
          const data = res.data
          this.curUsers = data.userGroupRelations ?? []
          this.values.forEach((item) => {
            if (['groupId', 'enabled'].indexOf(item.name) > -1) {
            } else {
              this.$refs.form.setFieldValue(item.name, data[item.name])
            }
          })
          if (data.enabled === 1) {
            this.$refs.form.setFieldValue('enabled', '1')
          } else {
            this.$refs.form.setFieldValue('enabled', '0')
          }

          this.$refs.form.setFieldValue('groupId', [
            { key: data.groupId.toString(), title: data.groupName },
          ])
        })
      } else {
        Promise.all([]).then(() => {
          this.values.forEach((item) => {
            if (['groupId', 'enabled'].indexOf(item.name) > -1) {
            } else {
              this.$refs.form.setFieldValue(item.name, undefined)
            }
          })

          this.$refs.form.setFieldValue('groupId', [
            { key: this.curParent.id, title: this.curParent.text },
          ])
        })
      }
    },
    save() {
      return new Promise((resolve) => {
        this.$refs.form.validateFields().then((success) => {
          if (success) {
            let params = {
              props: {},
            }
            if (this.unid) {
              params = {
                ...this.curNav,
                props: {},
              }
            }
            params.userGroupRelations = this.curUsers.map((item) => {
              return {
                userId: item.userId,
              }
            })
            this.$refs.form.getBackendValues().forEach((item) => {
              params[item.name] = item.value
              if (item.name === 'groupId') params[item.name] = JSON.parse(item.value)[0].key
              if (item.name === 'enabled') params[item.name] = item.value === '1' ? 1 : 0
            })
            this.loadingMsg = message.loading({
              key: this.msgKey,
              content: '处理中...',
              duration: 0,
            })
            if (this.unid) {
              params.id = this.unid
              return OrgService.group
                .updateDoc(params)
                .then((res) => {
                  if (res.status === 200) {
                    message.success('保存成功')
                    resolve(true)
                  } else {
                    message.error(res.data?.message || '保存失败')
                  }
                })
                .catch((res) => {
                  message.error(res?.response?.data?.message || '保存失败')
                })
                .finally(() => {
                  this.loadingMsg?.()
                })
            } else {
              return OrgService.group
                .createDoc({
                  data: {
                    ...params,
                  },
                })
                .then((res) => {
                  if (res.status === 200) {
                    message.success('新建成功')
                    resolve(true)
                  } else {
                    message.error(res.data?.message || '新建失败')
                  }
                })
                .catch((res) => {
                  message.error(res?.response?.data?.message || '新建失败')
                })
                .finally(() => {
                  this.loadingMsg?.()
                })
            }
          }
        })
      })
    },
    changeParentId(oNode) {
      if (oNode[0]) {
        this.$refs.form.setFieldValue('parentId', [parseInt(oNode[0].key, 10)])
      } else {
        this.$refs.form.setFieldValue('parentId', [])
      }
    },
    onLoadTreeData(parentCatId, parentCatObj) {
      return new Promise((resolve) => {
        if (parentCatId) {
          return OrgService.getOrgDepTree({ id: parentCatId }).then((deps) => {
            resolve(this.parseTreeData(deps.data))
          })
        } else {
          return OrgService.getOrgDepRoot().then((roots) => {
            resolve(this.parseTreeData(roots.data))
          })
        }
      })
    },
    parseTreeData(deps) {
      return deps.map((dep) => {
        return {
          key: dep.id,
          title: dep?.props?.hierarchical === 'true' ? dep.text + '(已开启分级)' : dep.text,
          name: dep.text,
          isLeaf: dep.leaf,
          scopedSlots: {
            title: 'title',
          },
          originalNode: {
            ...dep,
          },
        }
      })
    },
    selectedChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    updateData(data) {
      // 群组已经保存过，成员排序需发送请求保存
      if (this.unid) {
        const oldCurUsers = cloneDeep(this.curUsers)
        OrgService.sortOrgGroup(data.map((d) => d.id)).catch((e) => {
          this.curUsers = oldCurUsers
          message.error('排序失败')
        })
      }
      this.curUsers = data.map((d, i) => ({ ...d, sortNumber: i + 1 }))
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.operation-wrapper {
  width: 100%;
  overflow: hidden;
  :global(.ant-space) {
    float: right;
  }
}
</style>
