<template>
  <a-card>
    <component
      :is="computedAppId ? SdDataTableEx : SdDataTableSys"
      ref="htmbTable"
      ex
      form-id="oaRedhead"
      page-id="doc/redhead/oaRedhead"
      :columns="columns"
      :filter-expressions="expressions"
      show-selection
      :actions="actions"
      :search-fields="['redheadName']"
    >
      <template v-slot:form="{ model, fields }">
        <sd-form-item
          v-if="computedAppId"
          name="appId"
          hidden
          :input-props="{ defaultValue: computedAppId }"
        />
        <sd-form-item name="redheadName">
          <a-input
            v-model="model.redheadName"
            :max-length="30"
            placeholder="模板名称最长输入30字符"
          />
        </sd-form-item>
        <sd-form-item name="attachment"></sd-form-item>
        <sd-form-item name="authRange" />
        <sd-form-item v-if="model.authRange === 'range'" name="rangeDeptMember">
          <div :class="$style.deptcontent">
            <sd-group-picker
              v-model="model.rangeDeptMember"
              hierarchical
              :root-node="getRootNode(fields.rangeDeptMember)"
            />
            <a-checkbox :checked="model.authSubInclude === '1'" @change="setAuthSub">
              含下级</a-checkbox
            >
          </div>
        </sd-form-item>
        <sd-form-item
          v-if="model.authRange === 'range'"
          name="rangeUserMember"
          :input-props="{ rootNode: getRootNode(fields.rangeUserMember) }"
        />
        <sd-form-item name="sortNum" />
        <sd-form-item name="status"></sd-form-item>
      </template>
    </component>
    <!-- 批量导入 -->
    <a-modal
      v-model="isBulkImport"
      title="正文模版批量导入"
      destroy-on-close
      v-bind="{ width: 800 }"
      :mask-closable="false"
      @ok="bulkImport"
      @cancel="isBulkImport = false"
    >
      <sdForm ref="form" :init-values="bulkData">
        <sd-form-item name="attachment"></sd-form-item>
      </sdForm>
    </a-modal>
  </a-card>
</template>

<script>
import TableColumnTypes from '@/common/services/table-column-types'
import asyncComponent from '@/common/services/async-component'
import TableActionTypes from '@/common/services/table-action-types'
import { Message } from 'ant-design-vue'
import axios from '@/common/services/axios-instance'
import components from './_import-components/sd-zwmb-list-import'

const columns = [
  {
    title: '排序号',
    dataIndex: 'sortNum',
    defaultSortOrder: 'ascend',
    width: '10%',
  },
  {
    title: '模板名称',
    dataIndex: 'redheadName',
    sdClickable: true,
    width: '50%',
  },
  {
    title: '创建时间',
    dataIndex: 'creationTime',
    sdRender: TableColumnTypes.dateTime,
    sorter: true,
    defaultSortOrder: 'descend',
  },
  {
    title: '状态',
    dataIndex: 'status',
    sdRender: TableColumnTypes.ex.switch, // 特殊处理的类型，点击switch会自动处理真假值的切换
    width: '10%',
  },
]

export default {
  name: 'SdZwmbList',
  metaInfo: {
    title: '正文模板管理',
  },
  components: {
    ...components,
    sdForm: () => import('@/common/components/sd-form'),
  },
  props: {
    appId: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      showform: false,
      confirmLoading: false,
      columns,
      isBulkImport: false,
      actions: [
        {
          label: '批量导入',
          id: 'import',
          permission: null,
          callback: () => {
            this.isBulkImport = true
          },
        },
        {
          label: '新建',
          id: 'new',
          type: TableActionTypes.ex.create,
        },
        {
          label: '删除',
          id: 'delete',
          type: TableActionTypes.ex.delete, // 删除按钮，不需要回调，会自动处理（对sd-data-table无效）
        },
      ],
      bulkData: [],
      routeAppId: '',
    }
  },
  computed: {
    computedAppId() {
      return this.appId || this.routeAppId
    },
    expressions() {
      const expressions = []
      if (this.computedAppId) {
        expressions.push({
          dataType: 'str',
          name: 'appId',
          op: 'eq',
          stringValue: this.computedAppId,
        })
      } else {
        expressions.push({
          dataType: 'str',
          name: 'appId',
          op: 'is_null',
        })
      }
      return expressions
    },
  },
  created() {
    this.SdDataTableEx = asyncComponent(() =>
      import(/* webpackChunkName: "sd-data-table" */ '@/common/components/sd-data-table-ex.vue')
    )
    this.SdDataTableSys = asyncComponent(() =>
      import(/* webpackChunkName: "sd-data-table" */ '@/common/components/sd-data-table-sys.vue')
    )
    this.routeAppId = this.$route.query.appId
  },
  mounted() {
    this.getData()
  },
  methods: {
    getRootNode(field) {
      const belongedOrg = this.computedAppId ? null : this.$refs.htmbTable.getHierarchy()
      // 页面上有选择分级，返回当前分级
      if (belongedOrg) {
        return [{ code: belongedOrg.id, ...belongedOrg }]
      } else {
        // 以接口返回的roots为准
        return field.attr?.roots?.map((root) => {
          return { code: root.id, ...root }
        })
      }
    },
    getData() {
      // 先把正文模板功能挪到sd目录下，接口再看要不要改
      axios({
        method: 'get',
        url: `api/framework/v1/page/wp/doc/redhead/oaRedheadBatch`,
      }).then((res) => {
        this.bulkData = res.data.pageFormData.pageFieldInfos
      })
    },
    bulkImport() {
      const groupCode = JSON.parse(this.bulkData.find((item) => item.name === 'attachment').value)
        .value
      let params = ''
      if (this.computedAppId) {
        params += '&appId=' + this.computedAppId
      }
      if (!this.computedAppId) {
        const belongedOrg = this.$refs.htmbTable.getHierarchy()
        params += belongedOrg ? `&belongedOrgId=${belongedOrg.id}` : ''
      }
      axios({
        method: 'post',
        url: `api/framework/v1/redhead-manager/batch-upload?groupCode=${groupCode}&status=1${params}`,
      })
        .then((res) => {
          Message.success('上传成功')
          this.isBulkImport = false
          this.$refs.htmbTable.refresh()
        })
        .catch((err) => {
          Message.error(err)
        })
    },
    setAuthSub(e) {
      this.$refs.htmbTable
        .getDetailModal()
        .setFieldValue('authSubInclude', e.target.checked ? '1' : '0')
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.deptcontent {
  display: flex;
  justify-content: space-between;
  :global(.ant-checkbox-wrapper) {
    width: 21%;
    text-align: right;
  }
}
</style>
