<template>
  <span>
    <sd-webflow
      ref="docform"
      :validate-form="validForm"
      :removed-tabs="['sdRelatedDoc']"
      :class="$style.form"
      @actionBtnClick="actionBtnClick"
    >
      <template v-slot:form="{ model, fields, FlowData }">
        <table>
          <colgroup>
            <col style="width: 15%;"/>
            <col style="width: 35%;"/>
            <col style="width: 15%;"/>
            <col style="width: 35%;"
          /></colgroup>
          <tr v-show="false">
            <!-- 标题 -->
            <sd-form-item-td name="title" :colspan="3" />
          </tr>
          <tr>
            <td colspan="4" style="border:none">
              <audit-advanced-group
                :expand="expandJ"
                :expand-str="'expandJ'"
                :group-label="'基本信息'"
                @changedClick="changedClick"
              />
            </td>
          </tr>
          <tr v-show="expandJ">
            <!-- 申请人 -->
            <sd-form-item-td name="creatorName" />
            <!-- 公司 -->
            <sd-form-item-td name="createDeptName" />
          </tr>
          <tr v-show="expandJ">
            <!-- 申请时间 -->
            <sd-form-item-td name="creationTime" />
            <!-- 授权类型 -->
            <sd-form-item-td name="empowerType">
              <template>
                <a-select v-model="model.empowerType" @change="changeType">
                  <a-select-option
                    v-for="(key, i) in fields.empowerType.attr.selectListItem"
                    :key="i"
                    :value="key.value"
                  >
                    {{ key.label }}
                  </a-select-option>
                </a-select>
              </template>
            </sd-form-item-td>
          </tr>

          <tr v-if="model.empowerType === '1' && expandJ">
            <td class="ant-form-item-label ant-form-item-label">
              <label title="开始日期"> 开始日期 </label>
            </td>
            <td class="ant-form-item-control-wrapper">
              <a-date-picker v-model="model.startDate" :disabled="true" />
            </td>
            <td class="ant-form-item-label ant-form-item-label">
              <label title="结束日期"> 结束日期 </label>
            </td>
            <td class="ant-form-item-control-wrapper">
              <a-date-picker v-model="model.endDate" :disabled="true" />
            </td>
          </tr>
          <tr v-if="model.empowerType !== '1' && expandJ">
            <!-- 授权开始时间 -->
            <!-- <sd-form-item-td name="startDate" /> -->
            <!-- 授权截止时间 -->
            <!-- <sd-form-item-td name="endDate" /> -->
            <td class="ant-form-item-label ant-form-item-label">
              <label title="开始日期" class="ant-form-item-required"> 开始日期 </label>
            </td>
            <td class="ant-form-item-control-wrapper">
              <a-form-model-item :label="null" :rules="rules" prop="startDate">
                <a-date-picker v-model="model.startDate" />
              </a-form-model-item>
            </td>
            <td class="ant-form-item-label ant-form-item-label">
              <label title="结束日期" class="ant-form-item-required"> 结束日期 </label>
            </td>
            <td class="ant-form-item-control-wrapper">
              <a-form-model-item :label="null" :rules="rules" prop="endDate">
                <a-date-picker v-model="model.endDate" />
              </a-form-model-item>
            </td>
          </tr>
          <tr v-show="expandJ">
            <!-- 申请原因 -->
            <sd-form-item-td name="empowerReason" :colspan="3">
              <a-textarea v-model="model.empowerReason" :rows="3" />
            </sd-form-item-td>
          </tr>

          <tr
            ><td
              v-if="getmaintaindata(model, fields)"
              :colspan="4"
              style="line-height:40px;border:none1;"
              :class="$style.maintaintable"
            >
              <audit-advanced-group
                :expand="expandY"
                :expand-str="'expandY'"
                :group-label="'模型列表'"
                @changedClick="changedClick"
                ><template>
                  <!-- </td></tr><tr><td v-if="getmaintaindata(model,fields)" :colspan="4" :class="$style.maintaintable"  style="border:none"> -->
                  <div :class="$style.wrapper">
                    <div v-show="expandY && maintaineditable" :class="$style.btnselectmaintain">
                      <a-button type="link" :class="$style.batchselect" @click="mxRelSelect">
                        <a-icon type="check-circle" :theme="'filled'" />
                        选择
                      </a-button>
                      <a-button
                        type="link"
                        :disabled="selectedRowKeys.length === 0"
                        style="z-index:10"
                        @click="removemx(selectedRowKeys)"
                      >
                        <a-icon type="minus-circle" :theme="'filled'" />
                        删除
                      </a-button>
                    </div>
                  </div>
                  <sd-table
                    v-show="expandY"
                    ref="maintaintable"
                    :row-key="(record, index) => index"
                    :loading="false"
                    class="maintaintable"
                    :columns="childMXColumns"
                    :data-source="maintaindata"
                    :pagination="false"
                    :bordered="true"
                    :row-selection="
                      maintaineditable
                        ? {
                            getCheckboxProps(record) {
                              return {
                                props: { disabled: !showSelection(record) },
                              }
                            },
                            selectedRowKeys: selectedRowKeys,
                            onChange: onSelectChange,
                          }
                        : null
                    "/></template
              ></audit-advanced-group>
            </td>
          </tr>

          <tr
            ><td :colspan="4" style="border:none1">
              <sd-form-item name="iamLicenseUnitEntitys" :label="null">
                <template v-slot:read-and-edit="{ editable }">
                  <audit-advanced-group
                    :expand="expandW"
                    :expand-str="'expandW'"
                    :group-label="'申请单位'"
                    @changedClick="changedClick"
                    ><template>
                      <template>
                        <div :class="$style.wrapper">
                          <div v-show="expandW && editable" :class="$style.btnselect">
                            <a-button type="link" :class="$style.batchselect" @click="dwRelSelect">
                              <a-icon type="check-circle" :theme="'filled'" />
                              选择
                            </a-button>
                          </div>
                        </div>
                      </template>
                      <xm-child-table
                        v-model="model.iamLicenseUnitEntitys"
                        :read-only="!editable"
                        label=""
                        :fields="
                          [
                            {
                              caption: '序号',
                              name: 'sortNum',
                              dataType: 'sortNum',
                            },
                          ].concat(Array.from(fields.iamLicenseUnitEntitys.attr.dync))
                        "
                        :columns="childDWColumns"
                        :width="1200"
                        :addbuttonvisiable="false"
                        @change="saveForm"
                      >
                        <template v-slot:unitName="{ field, text, index, value }">
                          {{ text }}
                        </template>
                        <template v-slot:unitCode="{ field, text, index, value }">
                          {{ text }}
                        </template>
                      </xm-child-table>
                    </template>
                  </audit-advanced-group>
                </template>
              </sd-form-item></td
            >
          </tr>
          <tr v-show="false">
            <sd-form-item-td name="iamLicensePeopleEntitys" :label="null" :colspan="3">
            </sd-form-item-td>
          </tr>
        </table>
      </template>
    </sd-webflow>

    <AuditSelectMaintain :visible="visibleY" @listMxSelected="listMxSelected">
    </AuditSelectMaintain>
    <div v-show="false">
      <sd-group-picker
        ref="dwRelSelect"
        v-model="mainSendUnit"
        :single="false"
        :read-only="false"
        @change="change"
      />
    </div>
    <roleModal v-model="roleShow" @selectRoleList="changeRole" />
    <projectModal v-model="projectShow" @selectProject="changeProject" />
  </span>
</template>

<script>
import { Modal } from 'ant-design-vue'
import auditAdvancedGroup from '../../components/audit-advanced-group.vue'
import auditAdvancedGroupMixins from '../../components/audit-advanced-group-mixins'
import auditMaintainService from './audit-maintain-service'
import AuditSelectMaintain from './audit-select-maintain.vue'
import roleModal from '../dataUphold/role-modal.vue'
import projectModal from '../dataUphold/project-modal.vue'
import components from './_import-components/audit-sqapply-from-import'

export default {
  name: 'AuditDataSqapplyFrom',
  metaInfo: {
    title: '数据授权申请',
  },
  components: {
    ...components,
    auditAdvancedGroup,
    AuditSelectMaintain,
    roleModal,
    projectModal,
  },
  mixins: [auditAdvancedGroupMixins],
  data() {
    return {
      mainSendUnit: [],
      expandY: true,
      expandW: true,
      expandJ: true,
      visibleY: false,
      childMXColumns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: '模型名称',
          dataIndex: 'modelName',
        },
        {
          title: '模型编号',
          dataIndex: 'modelCode',
        },
        {
          title: '模型描述',
          dataIndex: 'modelDesc',
        },
      ],
      childDWColumns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        { dataIndex: 'id', sdHidden: true },
        { dataIndex: 'maintainId', sdHidden: true },
        {
          title: '单位名称',
          dataIndex: 'unitName',
        },
        {
          title: '单位编号',
          dataIndex: 'unitCode',
        },
        {
          title: '单位Id',
          dataIndex: 'unitId',
          sdHidden: true,
        },
      ],
      maintaindata: [],
      selectedRowKeys: [],
      flag: true,
      maintaineditable: false,
      rules: [
        {
          required: true,
          trigger: ['change', 'blur'],
        },
      ],
      roleShow: false,
      projectShow: false,
    }
  },
  watch: {
    maintaindata() {
      this.saveForm()
    },
  },
  methods: {
    changeType() {
      const empowerType = this.$refs.docform.getFieldValue('empowerType')
      if (empowerType === '1') {
        this.$refs.docform.setFieldValue('startDate', '')
        this.$refs.docform.setFieldValue('endDate', '')
      }
      this.saveForm()
    },
    getmodelsqdata(model) {
      this.mainSendUnit = []
    },
    saveForm() {
      const save = new Promise((resolve) => {
        let udata = []
        if (this.$refs.docform.getFieldValue('iamLicenseUnitEntitys') !== undefined) {
          udata = this.$refs.docform.getFieldValue('iamLicenseUnitEntitys')
        }
        if (this.maintaindata.length > 0) {
          const empowerType = this.$refs.docform.getFieldValue('empowerType')
          const creatorName = this.$refs.docform.getFieldValue('creatorId')
          const createDeptName = this.$refs.docform.getFieldValue('createDeptName')
          let sl = null
          let el = null
          if (empowerType === '0') {
            if (this.$refs.docform.getFieldValue('startDate') !== undefined) {
              const s = new Date(this.$refs.docform.getFieldValue('startDate'))
              const e = new Date(this.$refs.docform.getFieldValue('endDate'))
              sl = s.getTime()
              el = e.getTime()
            }
          }
          const maintainId = this.maintaindata.map((item) => item.id).join(',')
          udata.forEach((item) => {
            item.docType = 'date'
            item.maintainId = maintainId
            item.empowerType = empowerType
            item.startDate = sl
            item.endDate = el
          })
          this.$refs.docform.setFieldValue('iamLicenseUnitEntitys', udata)
          // 处理人员数据
          let pdata = []
          if (this.$refs.docform.getFieldValue('iamLicensePeopleEntitys') !== undefined) {
            pdata = this.$refs.docform.getFieldValue('iamLicensePeopleEntitys')
          }
          this.maintaindata.forEach((item) => {
            // 判断当前模型ID是否存在，存在则值处理 期间 日期 否则增加，处理过的增加标志位
            const m = pdata.find((p) => p.maintainId === item.id)
            if (m) {
              m.flag = true
              m.empowerType = empowerType
              m.startDate = sl
              m.endDate = el
            } else {
              pdata.push({
                docType: 'apply',
                empowerType: empowerType,
                startDate: sl,
                endDate: el,
                userId: creatorName + '',
                userUnit: createDeptName,
                maintainId: item.id,
                flag: true,
              })
            }
          })
          pdata.forEach((item, index) => {
            if (!item.flag) {
              pdata.splice(index, 1)
            } else {
              item.flag = null
            }
          })
          this.$refs.docform.setFieldValue('iamLicensePeopleEntitys', pdata)
        }
        // return Promise.resolve(true)
        resolve(true)
      })
      return save
    },
    validForm() {
      if (this.maintaindata.length === 0) {
        Modal.warning({
          title: '提示',
          content: '请选择需要授权的模型!',
        })
        return Promise.resolve(false)
      } else {
        // const udata = this.$refs.docform.getFieldValue('iamLicenseUnitEntitys')
        // if (udata.length === 0) {
        //   Modal.warning({
        //     title: '提示',
        //     content: '请选择授权单位!',
        //   })
        //   return Promise.resolve(false)
        // } else {
        this.$refs.docform.setFieldValue(
          'title',
          this.$refs.docform.getFieldValue('creatorName') + '模型授权申请'
        )
        return Promise.resolve(true)
        // }
      }
    },
    actionBtnClick(evt, { button, FlowData }) {
      if (button.fakeId === 'save' || button.fakeId === 'workflow-push') {
        // 保存前先校验计划是否已经存在
        evt.waitUntil(
          new Promise((resolve, reject) => {
            this.saveForm().then((res) => {
              if (!res) {
                evt.preventDefault()
              }
              resolve()
            })
          })
        )
      }
    },
    removemx(keys) {
      // 用的序号作key，从大往小删，防止串了
      const removeKeys = keys.sort((a, b) => b - a)
      removeKeys.forEach((key) => {
        this.maintaindata.splice(key, 1)
      })
      this.selectedRowKeys = []
    },
    getmaintaindata(model, fields) {
      if (this.flag) {
        this.maintaineditable = !fields.iamLicenseUnitEntitys.readonly
        const id = model.id
        if (id) {
          auditMaintainService.getmaintainsqdata(id).then((data) => {
            this.maintaindata = data
            this.getmodelsqdata(model)
          })
        }
        this.flag = false
      }
      return true
    },
    showSelection() {
      return true
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    change(values) {
      let iamAuditDwMxs = []
      if (this.$refs.docform.getFieldValue('iamLicenseUnitEntitys')) {
        iamAuditDwMxs = this.$refs.docform.getFieldValue('iamLicenseUnitEntitys')
      }

      values.forEach((element) => {
        const mmc = {}
        mmc.unitName = element.name
        // mmc.unitCode = element.props?.code
        mmc.unitCode = element.code + ''
        mmc.unitId = element.code
        iamAuditDwMxs.push(mmc)
      })
      this.$refs.docform.setFieldValue('iamLicenseUnitEntitys', iamAuditDwMxs)
      this.saveForm()
    },

    // 选择模型列表
    mxRelSelect() {
      // 选择模型列表
      this.visibleY = true
    },
    // 选择申请单位
    dwRelSelect() {
      // 选择申请单位
      setTimeout(() => {
        this.$refs.dwRelSelect.openPicker()
      }, 0)
    },

    listMxSelected(keys, keyinfos) {
      let iamAuditMxs = []
      iamAuditMxs = this.maintaindata

      keyinfos.forEach((element) => {
        const mmc = {}
        mmc.modelName = element.modelName
        mmc.modelCode = element.modelCode
        mmc.modelDesc = element.modelDesc
        mmc.id = element.id
        iamAuditMxs.push(mmc)
      })
      this.maintaindata = iamAuditMxs
      // 处理人员数据-仅增加新增的
      // pdata.forEach((item) => {
      //   item.docType = 'apply'
      //   item.maintainId = maintainId
      // })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
@import '@/webflow/sd-flow-form.scss';

.btnselect {
  position: relative;
  top: 2px;
  right: 80px;
  float: right;
  .batchselect {
    z-index: 100;
    margin-left: 10px;
  }
}
.btnselectmaintain {
  position: relative;
  float: right;
  .batchselect {
    z-index: 100;
    margin-right: -10px;
    margin-left: 10px;
  }
}
.maintaintable {
  :global(.ant-table-thead > tr > th) {
    border-right: none;
  }
  :global(.ant-table-bordered.ant-table-empty .ant-table-placeholder) {
    border: none;
  }
  :global(.ant-table-body table) {
    //  border-left:none;
    border: none;
  }
}
</style>
