<template>
  <sd-form ref="form" :key="updateKey" :init-values="values" :read-only="!editable">
    <template>
      <sd-form-item
        v-for="item in values"
        :key="item.name"
        :name="item.name"
        :input-props="item.name === 'code' ? { readOnly: unid && unid !== '' ? true : false } : {}"
      >
        <template v-if="item.name === 'parentId'" v-slot:read-and-edit>
          <template v-if="editable">
            <sd-value-picker
              v-model="parentInfo"
              single
              option-value="key"
              option-label="title"
              @change="changeParentId"
            >
              <template v-slot="scope">
                <sd-picker-source-tree :load-tree-data="onLoadTreeData" v-bind="scope" />
              </template>
            </sd-value-picker>
          </template>
          <template v-else> {{ parentInfo ? parentInfo[0].title : '' }} </template>
        </template>
        <template v-if="item.name === 'level'" v-slot:read>
          {{ level }}
        </template>
      </sd-form-item>
    </template>
  </sd-form>
</template>

<script>
import { message } from 'ant-design-vue'
import OrgService from './org-service'
import components from './_import-components/sd-org-dep-import'

export default {
  name: 'SdOrgDep',
  metaInfo: {
    title: 'SdOrgDep',
  },
  components,
  props: {
    unid: {
      type: String,
      default: function () {
        return null
      },
    },
    curParent: {
      type: Object,
      default: function () {
        return null
      },
    },
    editable: {
      type: Boolean,
      default: function () {
        return true
      },
    },
    isBatch: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      parentInfo: null,
      level: '',
      updateKey: 0,
      values: [
        {
          name: 'code',
          caption: '机构代码',
          dataType: 'string',
          required: true,
        },
        {
          name: 'name',
          caption: '名称',
          required: true,
          dataType: 'string',
        },
        {
          name: 'parentId',
          caption: '上级机构',
          dataType: 'number',
          required: true,
        },
        {
          name: 'level',
          caption: '机构级别',
          dataType: 'selectlist',
          value: null,
          attr: {
            selectListItem: [],
          },
        },
        {
          name: 'ifzb',
          caption: '是否总部',
          dataType: 'selectlist',
          value: null,
          attr: {
            selectListItem: [
              { value: '', label: '空' },
              { value: '1', label: '是' },
              { value: '0', label: '否' },
            ],
          },
        },
        {
          name: 'weight',
          caption: '排序号',
          dataType: 'number',
        },
        {
          name: 'description',
          caption: '备注信息',
          dataType: 'string',
        },
      ],
      batchFields: ['parentId', 'level'],
    }
  },
  watch: {
    unid: {
      handler(newVal, oldVal) {
        this.getByStep()
      },
      immediate: true,
    },
  },
  created() {
    // 批量修改，只允许修改：上级机构、机构级别
    if (this.isBatch) {
      this.values = this.values.filter((f) => this.batchFields.includes(f.name))
    }
  },
  methods: {
    getByStep() {
      OrgService.getOrgLevel({ code: 'G' }).then((res) => {
        this.values.forEach((item) => {
          if (item.name === 'level')
            item.attr.selectListItem = res.data.datas.map((opt) => {
              return {
                value: opt.code,
                label: opt.name,
              }
            })
        })
        this.updateKey++
        this.getDefaultValue()
      })
    },
    getDefaultValue() {
      if (this.unid) {
        OrgService.getOrgDep({ id: this.unid }).then((res) => {
          const data = res.data
          this.values.forEach((item) => {
            if (item.name === 'level') {
              this.$refs.form.setFieldValue(item.name, data.props?.lev)
              this.level = data.level
            } else {
              this.$refs.form.setFieldValue(item.name, data[item.name])
            }
          })
          this.$refs.form.setFieldValue('parentId', [data.parentId])
          this.parentInfo = [{ key: data.parentId.toString(), title: data.parentName }]
          if ('ifzb' in data.props) {
            this.$refs.form.setFieldValue('ifzb', data.props?.ifzb)
          } else {
            this.$refs.form.setFieldValue('ifzb', '')
          }
        })
      } else {
        // 修改信息（非批量修改）
        if (!this.isBatch) {
          // 获取当前层级下组织的最大排序号
          OrgService.getOrgDepList({
            expressions: [
              {
                name: 'parentId',
                op: 'eq',
                dataType: 'str',
                stringValue: this.curParent.id,
              },
            ],
            orderBy: 'weight desc',
            maxResults: 1,
          }).then((res) => {
            const weight = res.data.datas?.[0]?.weight || 0
            this.$refs.form.setFieldValue('weight', weight + 1)
          })
        }

        Promise.all([]).then(() => {
          this.$refs.form.setFieldValue('parentId', [parseInt(this.curParent.id, 10)])
          this.parentInfo = [{ key: this.curParent.id.toString(), title: this.curParent.text }]
        })
      }
    },
    save(ids) {
      return new Promise((resolve) => {
        let saveFlag = false
        this.$refs.form
          .validateFields()
          .then((success) => {
            if (success) {
              const params = {
                props: {},
              }
              this.$refs.form.getBackendValues().forEach((item) => {
                params[item.name] = item.value
                if (item.name === 'parentId') params[item.name] = JSON.parse(item.value)[0]
                if (item.name === 'level') params.props.lev = item.value ? item.value : ''
                if (item.name === 'ifzb') params.props.ifzb = item.value ? item.value : ''
              })
              let p, action
              if (this.isBatch) {
                action = '批量修改'
                p = OrgService.batchUpdateOrgDep({ group: params, ids })
              } else {
                if (this.unid) {
                  action = '保存'
                  params.id = this.unid
                  p = OrgService.saveOrgDep(params)
                } else {
                  action = '新建'
                  p = OrgService.createOrgDep(params)
                }
              }
              return p.then((res) => {
                if (res.status === 200) {
                  message.success(action + '成功')
                  saveFlag = true
                } else {
                  message.error(res.data?.message || action + '失败')
                }
              })
            }
          })
          .finally(() => {
            resolve(saveFlag)
          })
      })
    },
    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',
          },
        }
      })
    },
  },
}
</script>

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