<template>
  <a-card>
    <sd-data-table-ex
      form-id="weThirdSysConfig"
      page-id="extracirc/sysconfig/weThirdSysConfig"
      :columns="columns"
      :actions="actions"
      show-selection
      :modal-props="{ width: '1000px' }"
      :search-fields="['sys_name']"
    >
      <template v-slot:form="{ model, fields }">
        <sd-form-item name="sysCode" />
        <sd-form-item name="sysName" />
        <sd-form-item name="status" />
        <sd-form-item name="sysInterfaceType" />
        <sd-form-item name="sysEndUrl" />
        <sd-form-item name="wsdl" />
        <sd-form-item name="authenIs" />
        <sd-form-item name="tokenUrl" />
        <sd-form-item name="interfaceType" />

        <sd-form-item name="mqHost" :hidden="!['4', '5'].includes(model.sysInterfaceType)" />
        <sd-form-item name="mqPort" :hidden="!['4', '5'].includes(model.sysInterfaceType)" />
        <sd-form-item name="virtualHost" />
        <sd-form-item name="mqUserName" />
        <sd-form-item name="mqPassword" />
        <sd-form-item name="rabbitExchangeTopic" />
        <sd-form-item name="rabbitRoutkey" />
        <sd-form-item name="rocketProducerGroup" />
        <sd-form-item name="rocketTopic" />
        <sd-form-item name="resValue" />

        <sd-form-item name="param1">
          <a-textarea v-model="model.param1" />
        </sd-form-item>
        <sd-form-item name="param2">
          <a-textarea v-model="model.param2" />
        </sd-form-item>
        <sd-form-item name="param3">
          <a-textarea v-model="model.param3" />
        </sd-form-item>
        <sd-form-item name="param4">
          <a-textarea v-model="model.param4" />
        </sd-form-item>
        <sd-form-item name="param5">
          <a-textarea v-model="model.param5" />
        </sd-form-item>
        <div>
          <sd-form-item name="weThirdSysConfigChildEntityList" :label="null">
            <template v-slot:read-and-edit="{ editable }">
              <sd-child-table
                ref="childForm"
                v-model="model.weThirdSysConfigChildEntityList"
                :columns="[
                  { dataIndex: 'businessTypeId', sdHidden: true },
                  { dataIndex: 'randomNumber', sdHidden: true },
                  { dataIndex: 'businessField', sdHidden: true },
                  { dataIndex: 'weThirdSysConfigConChildEntityList', sdHidden: true },
                ]"
                :label="fields.weThirdSysConfigChildEntityList.caption"
                :read-only="!editable"
                :fields="Array.from(fields.weThirdSysConfigChildEntityList.attr.dync)"
              >
                <span slot="returnOpinion" slot-scope="{ text }">{{
                  JSON.parse(text)[0].name
                }}</span>
                <template v-slot:form="scope">
                  <sd-form-item name="pushIs" />
                  <sd-form-item name="returnTime" />
                  <sd-form-item name="businessField">
                    <sd-business-type-picker v-model="scope.model.businessField" single />
                  </sd-form-item>
                  <sd-form-item name="allOpinion" />
                  <sd-form-item v-if="scope.model.allOpinion === '0'" name="returnOpinion">
                    <sd-list-picker
                      v-if="scope.model.businessField && scope.model.businessField.length"
                      v-model="scope.model.returnOpinion"
                      option-value="stepId"
                      :load-list-data="() => loadListData(scope.model.businessField)"
                    />
                    <a-input v-else ref="input" @click="warn" />
                  </sd-form-item>
                  <sd-form-item name="transSysFlowCode">
                    <a-input v-model="scope.model.transSysFlowCode">
                      <a-tooltip
                        slot="suffix"
                        title="此字段用来和系统的code一起（系统的code_第三方系统流程使用的code，具体值是双方约定的）从第三方系统传入到OA系统中，用作查询具体的配置"
                      >
                        <a-icon type="question-circle-o" />
                      </a-tooltip>
                    </a-input>
                  </sd-form-item>
                  <sd-form-item name="transFileCode" />

                  <sd-form-item
                    name="randomNumber"
                    hidden
                    :input-props="{
                      defaultValue: new Date().getTime(),
                    }"
                  />
                  <sd-form-item name="isSubmit" />

                  <div>
                    <div :class="$style.thirdTable">
                      <span :class="$style.title">第三方配置子表-内容</span>
                      <sd-data-table-ex
                        ref="table"
                        form-id="weThirdSysConfigConChild"
                        page-id="extracirc/sysconfigconchild/weThirdSysConfigConChild"
                        :columns="childColumns"
                        :actions="childActions"
                        :filter-expressions="[
                          {
                            dataType: 'long',
                            name: 'randomNumber',
                            op: 'eq',
                            longValue: scope.model.randomNumber || '',
                          },
                        ]"
                        show-selection
                      >
                        <template v-slot:form="{ model: tableModel }">
                          <sd-form-item name="id" hidden />
                          <sd-form-item name="conType" />
                          <sd-form-item name="fieldName">
                            <a-input
                              ref="fieldNameInput"
                              v-model="tableModel.fieldName"
                              @click="
                                selectFieldName(tableModel.conType, scope.model.businessField)
                              "
                            />
                          </sd-form-item>
                          <sd-form-item name="fieldId">
                            <a-input v-model="tableModel.fieldId" disabled />
                          </sd-form-item>
                          <sd-form-item name="theFieldId" />
                          <sd-form-item
                            name="configChildId"
                            hidden
                            :input-props="{ defaultValue: scope.model.id }"
                          />
                          <sd-form-item
                            name="randomNumber"
                            hidden
                            :input-props="{ defaultValue: scope.model.randomNumber }"
                          />
                        </template>
                      </sd-data-table-ex>
                    </div>
                  </div>
                </template>
              </sd-child-table>
            </template>
          </sd-form-item>
        </div>
      </template>
    </sd-data-table-ex>
    <a-modal
      :visible="importVisible"
      title="导入文件"
      :width="800"
      destroy-on-close
      :confirm-loading="confirmImportLoading"
      @cancel="importVisible = false"
      @ok="handleImportExcelOk"
    >
      <sd-attachment v-model="files" :group-id="groupId" max="1" />
    </a-modal>
  </a-card>
</template>

<script>
import sdListPickerVue from '@/common/components/sd-list-picker.vue'
import download from '@/common/services/download'
import pickValues from '@/common/services/pick-values'
import TableActionTypes from '@/common/services/table-action-types'
import axios from '@/common/services/axios-instance'
import { message } from 'ant-design-vue'
import components from './_import-components/sd-sys-switchon-config-import'
const columns = [
  {
    dataIndex: 'id',
    sdHidden: true,
  },
  {
    dataIndex: 'sysName',
    title: '系统名称',
    sdClickable: true,
  },
  {
    dataIndex: 'sysCode',
    title: '系统标识',
  },
  {
    dataIndex: 'status',
    title: '状态',
  },
]
const childColumns = [
  {
    dataIndex: 'conType',
    title: '内容类型',
  },
  {
    dataIndex: 'fieldId',
    title: '字段id',
  },
  {
    dataIndex: 'fieldName',
    title: '字段名称',
    sdClickable: true,
  },
  {
    dataIndex: 'theFieldId',
    title: '第三方字段id',
  },
]
export default {
  name: 'SdSysSwitchonConfig',
  metaInfo: {
    title: '系统接入配置',
  },
  components,
  data() {
    const delAction = {
      label: '删除',
      id: 'delete',
      type: TableActionTypes.ex.delete,
    }
    return {
      visible: false,
      values: [],
      columns,
      childColumns,
      files: [],
      groupId: '',
      confirmImportLoading: false,
      importVisible: false,
      actions: [
        {
          label: '新建',
          id: 'new',
          type: TableActionTypes.ex.create,
        },
        {
          label: '导入',
          id: 'import',
          permission: null,
          type: TableActionTypes.common,
          callback: () => {
            this.getGroupId()
              .then((data) => {
                this.groupId = data
                this.importVisible = true
              })
              .catch((e) => {
                message.error(e.response?.data?.message || '获取groupId失败')
              })
          },
        },
        {
          label: '导出',
          id: 'export',
          permission: null,
          type: TableActionTypes.common,
          callback: this.exportExcel,
        },
        delAction,
      ],
      childActions: [
        {
          label: '新建',
          id: 'new',
          permission: null,
          type: 'primary',
          callback: () => {
            const businessField = this.$refs.childForm.$refs.form.model.businessField
            if (businessField && businessField.length) {
              this.$refs.table.showDetailModal()
            } else message.warning('请先选择业务类型！')
          },
        },
        delAction,
      ],
    }
  },
  methods: {
    warn() {
      this.$refs.input.blur()
      message.warning('请先选择业务类型！')
    },
    loadListData(businessField) {
      return axios
        .post('api/framework/v1/wethirdsysconfigchild/getOpinions', {
          businessTypeId: businessField[0].id,
        })
        .then((res) => {
          return res.data.map((item) => ({
            name: item.name,
            stepId: item.stepId,
          }))
        })
    },
    selectFieldName(conType, businessField) {
      this.$refs.fieldNameInput.blur()
      if (!conType) return message.warning('请先选择内容类型！')
      axios
        .post(
          `api/framework/v1/wethirdsysconfigchild/fieldInfos?businessTypeId=${businessField[0].id}&fieldType=${conType}`
        )
        .then((res) => {
          if (res.data) {
            pickValues(sdListPickerVue, {
              optionValue: 'id',
              optionLabel: 'text',
              singleColumn: true,
              single: true,
              loadListData: () => res.data,
            }).then((value) => {
              if (value) {
                this.$refs.table.getDetailModal().setFieldsValue({
                  fieldName: value[0].text,
                  fieldId: value[0].id,
                  theFieldId: value[0].id,
                })
                this.$refs.table.getDetailModal().validateFields()
              }
            })
          }
        })
    },
    getGroupId() {
      return axios
        .get('api/framework/v1/attachment-extend/attachments-create-group-code')
        .then((res) => {
          return res.data
        })
    },
    handleImportExcelOk() {
      if (this.files[0]) {
        if (this.files[0].Completed !== 1) {
          message.warn('您有文件还在上传中')
          return
        }
        this.confirmImportLoading = true
        const data = {
          id: '',
          code: this.files[0].code,
        }
        axios
          .post('api/xcoa-mobile/v1/wethirdsysconfig/import-excel', data)
          .then(() => {
            message.success('已导入')
            this.importVisible = false
          })
          .catch((e) => {
            message.error(e.response?.data?.message || '导入失败')
          })
          .finally(() => {
            this.confirmImportLoading = false
          })
      } else {
        message.warn('请上传文件')
      }
    },
    exportExcel() {
      download('api/xcoa-mobile/v1/wethirdsysconfig/export/excel', '体外审批中心配置.xls', true)
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.table {
  :global .ant-form-item:last-child {
    :global .ant-col {
      width: 100%;
    }
  }
}
.third-table {
  position: relative;
  .title {
    position: absolute;
    left: 50%;
    transform: translate(-50%, 0);
  }
}
.modal {
  :global .ant-modal {
    width: 1000px;
  }
}
</style>
