<template>
  <span>
    <audit-form-top-banner
      :handel-save-form="saveForm"
      :form-data="mode"
      @handelSaveForm="saveForm"
      @handelPublish="handelPublish"
    >
      <div class="ant-card ant-card-small">
        <div :class="$style.antCardBody">
          <sd-detail-form
            ref="docform"
            page-id="audit/auditsource/target/iamTarget"
            form-id="iamTarget"
            :record-id="this.$route.query.id ? parseInt(this.$route.query.id) : null"
            :class="[$style.form]"
            @close="close(true)"
            @saved="saved"
            @sdFormReady="sdFormReady"
          >
            <template v-slot="{ model, fields }">
              <table
                ><tr
                  ><td>
                    <audit-advanced-group
                      :expand="basicExpand"
                      :expand-str="'basicExpand'"
                      :group-label="'基本信息'"
                      tablestyle="''"
                      @changedClick="changedClick"
                    ></audit-advanced-group> </td></tr
              ></table>

              <table v-show="basicExpand" :class="$style.table">
                <colgroup>
                  <col :class="$style.label" />
                  <col :class="$style.input" />
                  <col :class="$style.label" />
                  <col :class="$style.input" />
                </colgroup>
                <tr>
                  <sd-form-item-td name="orgId">
                    {{ model.orgId }}
                  </sd-form-item-td>
                  <sd-form-item-td
                    name="targetDeptMember"
                    @change="targetDeptMemberChange(model)"
                  />
                  <!-- <sd-form-item-td name="targetDeptMember" @change="getOrgId(model)">
                    <AuditGroupPicker
                            ref="targetDeptMember"
                            v-model="model.targetDeptMember"
                            :single="true"
                            :read-only="false"
                            :root-node="rootNode"
                    />
                  </sd-form-item-td> -->
                </tr>
                <tr>
                  <sd-form-item-td name="address" />
                  <sd-form-item-td name="directorOperator"> </sd-form-item-td>
                </tr>
                <tr>
                  <sd-form-item-td name="contractOperator" />
                  <sd-form-item-td name="contract"> </sd-form-item-td>
                </tr>
                <!-- <tr class="iamtargetform">
                  <sd-form-item-td
                    name="whetherLeave"
                    :colspan="3"
                    @change="targetChange(model.whetherLeave, 'whetherLeave')"
                  />
                </tr> -->
                <tr class="bklabeloverflow">
                  <sd-form-item-td
                    name="whetherFinance"
                    @change="targetChange(model.whetherFinance, 'whetherFinance')"
                  />
                  <sd-form-item-td
                    name="whetherInclude"
                    @change="targetChange(model.whetherInclude, 'whetherInclude')"
                  />
                  <!-- <sd-form-item-td
                    name="whetherOverseas"
                    @change="targetChange(model.whetherOverseas, 'whetherOverseas')"
                  /> -->
                </tr>
                <tr>
                  <sd-form-item-td name="companyStatus" />
                </tr>
                <tr>
                  <!-- 经责审计规则 -->
                  <!-- <sd-form-item-td name="iamRule" readonly /> -->
                  <sd-form-item-td name="iamRule" label="经责审计规则">
                    <span>{{ getFormSelectFieldValue(model.iamRule) }}</span>
                  </sd-form-item-td>
                  <!-- <sd-form-item-td name="planIamYear" /> -->
                </tr>
                <tr>
                  <sd-form-item-td name="description" :colspan="3">
                    <a-textarea
                      v-model="model.description"
                      placeholder="请输入"
                      :auto-size="{ minRows: 3, maxRows: 5 }"
                    />
                  </sd-form-item-td>
                </tr>
                <tr>
                  <sd-form-item-td name="country" />
                  <sd-form-item-td name="region" />
                </tr>
                <tr>
                  <sd-form-item-td name="registerAddress" :colspan="3" />
                  <sd-form-item-td name="simple" :hidden="true" />
                </tr>

                <tr>
                  <!-- 作者 -->
                  <sd-form-item-td name="creatorName" />
                  <!-- 创建时间 -->
                  <sd-form-item-td name="creationTime" />
                </tr>
                <tr>
                  <!-- 维护人员所在单位 -->
                  <sd-form-item-td name="upholdDeptName" />
                </tr>
                <tr>
                  <!-- 附件 -->
                  <sd-form-item-td name="attachment" :colspan="3" />
                </tr>
              </table>

              <table>
                <tr
                  ><td :colspan="4">
                    <sd-form-item name="iamAuditedYearEntities" :label="null">
                      <template v-slot:read-and-edit="{ editable }">
                        <audit-advanced-group
                          :expand="projectExpand"
                          :expand-str="'projectExpand'"
                          :group-label="'全覆盖审计项目'"
                          @changedClick="changedClick"
                        >
                          <template>
                            <sd-child-table
                              ref="auditeYear"
                              v-model="model.iamAuditedYearEntities"
                              :class="$style.deptPlanChild"
                              label=""
                              :read-only="!editable"
                              :fields="
                                [
                                  {
                                    caption: '序号',
                                    name: 'sortNum',
                                    dataType: 'number',
                                    attr: {},
                                  },
                                ].concat(Array.from(fields.iamAuditedYearEntities.attr.dync))
                              "
                              :columns="auditeYearChildColumns"
                              :flagpage="true"
                              @change="changeNum"
                            >
                              <!-- input-form 表示这部分是子表组件的form插槽 -->

                              <template v-slot:form="{ model }">
                                <table style="width: 90%">
                                  <tr>
                                    <!-- 已审计年份 -->
                                    <sd-form-item-td name="auditedYear" />
                                  </tr>
                                  <tr>
                                    <sd-form-item-td name="projectName" :colspan="3" />
                                  </tr>
                                </table>
                              </template>
                            </sd-child-table>
                          </template>
                        </audit-advanced-group>
                      </template> </sd-form-item
                  ></td>
                </tr>
              </table>

              <table>
                <tr
                  ><td :colspan="4">
                    <sd-form-item name="iamTargetProjectEntities" :label="null">
                      <template v-slot:read-and-edit="{ editable }">
                        <audit-advanced-group
                          :expand="projectExpand"
                          :expand-str="'projectExpand'"
                          :group-label="'历史被审项目'"
                          @changedClick="changedClick"
                        >
                          <template>
                            <sd-child-table
                              ref="tabaData"
                              v-model="model.iamTargetProjectEntities"
                              :class="$style.deptPlanChild"
                              label=""
                              :read-only="!editable"
                              :fields="
                                [
                                  {
                                    caption: '序号',
                                    name: 'sortNum',
                                    dataType: 'number',
                                    attr: {},
                                  },
                                ].concat(Array.from(fields.iamTargetProjectEntities.attr.dync))
                              "
                              :columns="projectChildColumns"
                              :flagpage="true"
                              @change="changeNum"
                            >
                              <!-- input-form 表示这部分是子表组件的form插槽 -->

                              <template v-slot:form="{ model }">
                                <table style="width: 90%">
                                  <tr>
                                    <!-- 项目名称 -->
                                    <sd-form-item-td name="projectName" />
                                    <!-- 项目编号 -->
                                    <sd-form-item-td name="projectNo" />
                                  </tr>
                                  <tr>
                                    <!-- 审计机构 -->
                                    <sd-form-item-td name="auditOrg" />
                                    <!-- 被审计单位 -->
                                    <sd-form-item-td name="auditedUnit" />
                                  </tr>
                                  <tr>
                                    <!-- 项目组长 -->
                                    <sd-form-item-td name="projectHeadman" />
                                  </tr>
                                  <tr>
                                    <!-- 项目开始日期 -->
                                    <!-- 项目结束日期 -->
                                    <sd-form-item-td
                                      label="项目起止日期"
                                      :colspan="3"
                                      :name="['projectStartTime', 'projectEndTime']"
                                    />
                                  </tr>
                                  <tr>
                                    <!-- 审计期间开始时间 -->
                                    <!-- 审计期间结束时间 -->
                                    <sd-form-item-td
                                      label="审计期间"
                                      :colspan="3"
                                      :name="['auditStartTime', 'auditEndTime']"
                                    />
                                  </tr>
                                  <tr>
                                    <!-- 项目内容 -->
                                    <sd-form-item-td name="auditCondition" :colspan="3">
                                      <a-textarea v-model="model.auditCondition" :rows="4" />
                                    </sd-form-item-td>
                                  </tr>
                                  <tr>
                                    <!-- 维护人员 -->
                                    <sd-form-item-td name="creatorName" />
                                    <!-- 维护日期 -->
                                    <sd-form-item-td name="creationTime" />
                                  </tr>
                                  <tr>
                                    <!-- 附件 -->
                                    <sd-form-item-td name="attachment" :colspan="3" />
                                  </tr>
                                </table>
                              </template>
                            </sd-child-table>
                          </template>
                        </audit-advanced-group>
                      </template> </sd-form-item
                  ></td>
                </tr>
              </table>
            </template>
          </sd-detail-form>
        </div>
      </div>
    </audit-form-top-banner>
    <iam-audit-modal
      :single="false"
      :check-type="'radio'"
      select-type="table"
      :visible="visible"
      :treeparams="{
        configId: '11',
      }"
      :columns="columns"
      @listSelected="listSelected"
      @getCheckNode="getCheckNode"
    ></iam-audit-modal>
  </span>
</template>

<script>
import { Message, Modal } from 'ant-design-vue'
import axios from '@/common/services/axios-instance'
import { getUserInfo } from '@/common/store-mixin'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import sdDateFormat from '@/common/filters/sd-date-format'
import auditFormTopBanner from '../../../components/audit-form-top-banner'
import iamAuditModal from '../../../components/iam-audit-modal.vue'
import auditAdvancedGroup from '../../../components/audit-advanced-group.vue'
// import AuditGroupPicker from '../../../components/picker/audit-group-picker.vue'
import auditAdvancedGroupMixins from '../../../components/audit-advanced-group-mixins'
import components from './_import-components/iam-source-target-form-import'

export default {
  name: 'IamSourceTargetForm',
  metaInfo() {
    return {
      title: '审计对象',
    }
  },
  components: {
    auditFormTopBanner,
    ...components,
    auditAdvancedGroup,
    iamAuditModal,
    // AuditGroupPicker,
  },
  mixins: [auditAdvancedGroupMixins],
  data() {
    return {
      secUnitflag: null,
      rootNode: {},
      defaultCategory: '',
      labelArray: [],
      publishFlag: false,
      basicExpand: true,
      projectExpand: true,
      CheckExpand: true,
      visible: false,
      checkChildColumns: [
        { dataIndex: 'lawsLibraryId', sdHidden: true },
        { dataIndex: 'lawsType', sdHidden: true },
        {
          title: '序号',
          dataIndex: 'sortNum',
          width: '70px',
          customRender: (text, record, index) => `${index + 1}`,
        },
      ],
      projectChildColumns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          width: '80px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        { dataIndex: 'projectName', sdHidden: false },
        { dataIndex: 'projectNo', sdHidden: false, width: '150px' },
        { dataIndex: 'auditOrg', sdHidden: false, width: '180px' },
        { dataIndex: 'auditedUnit', sdHidden: true },
        { dataIndex: 'projectHeadman', sdHidden: false, width: '120px' },
        {
          dataIndex: 'projectStartEndTime',
          sdHidden: false,
          customRender: (text, record, index) => {
            var startTime = sdDateFormat(record.projectStartTime, 'yyyy-MM-DD')
            var endTime = sdDateFormat(record.projectEndTime, 'yyyy-MM-DD')
            return startTime + '~' + endTime
          },
        },
        { dataIndex: 'projectStartTime', sdHidden: true },
        { dataIndex: 'projectEndTime', sdHidden: true },
        { dataIndex: 'auditStartTime', sdHidden: true },
        { dataIndex: 'auditEndTime', sdHidden: true, title: '审计结束日期', width: '150px' },
        { dataIndex: 'auditCondition', sdHidden: false, width: '25%' },
        { dataIndex: 'creatorName', sdHidden: true },
        { dataIndex: 'creationTime', sdHidden: true },
        { dataIndex: 'attachment', sdHidden: true },
      ],
      auditeYearChildColumns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          width: '80px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        { dataIndex: 'auditedYear', width: '120px', sdHidden: false },
        { dataIndex: 'projectName', sdHidden: false },
      ],
      expressions: [],
      columns: [
        {
          title: '机构名称',
          dataIndex: 'orgName',
          width: '15%',
        },
        {
          title: '机构编码',
          dataIndex: 'orgId',
          width: '10%',
        },
      ],
      mode: null,
      iamRuleOptions: [],
    }
  },
  created() {
    let userInfo = getUserInfo()
    const params = {
      orgId: userInfo.deptId,
    }
    axios({
      url: 'api/xcoa-mobile/v1/iamorg/getCurrentUserGroup',
      method: 'get',
    }).then((res) => {
      userInfo = res.data
      params.orgId = res.data.id
      axios({
        url: 'api/xcoa-mobile/v1/iamorg/findIamOrgId',
        method: 'post',
        params,
      }).then((res) => {
        this.id = res.data
        const deptCode = userInfo.id.toString()
        const deptName = userInfo.name
        this.rootNode = { code: deptCode, name: deptName, id: this.id }
      })
    })
  },
  mounted() {
    axios({
      url: 'api/xcoa-mobile/v1/iam-law/dictionary?key=IAM_RULE',
      method: 'get',
    }).then((res) => {
      if (res.status === 200) {
        this.iamRuleOptions = res.data
      }
    })
  },
  methods: {
    // 页面加载完成后
    //  url: 'api/xcoa-mobile/v1/iamorg/getCurrentUserGroup',
    // url: 'api/xcoa-mobile/v1/iamtarget/getCreatorGroup',
    sdFormReady() {
      this.mode = this.$refs.docform.formData.mode
      debugger
      axios({
        url: 'api/xcoa-mobile/v1/iamtarget/getCreatorGroup',
        method: 'post',
      }).then((res) => {
        this.$refs.docform.setFieldValue('upholdDeptName', res.data.name)
        this.$refs.docform.setFieldValue('upholdDeptId', res.data.id)
        this.$refs.docform.setFieldValue('upholdDeptCode', res.data.code)
      })
    },
    targetChange(val, e) {
      debugger
      let iamRule = ''
      var targetDeptMember = this.$refs.docform.getFieldValue('targetDeptMember')
      const whetherFinance = this.$refs.docform.getFieldValue('whetherFinance')
      // const whetherOverseas = this.$refs.docform.getFieldValue('whetherOverseas')
      const whetherInclude = this.$refs.docform.getFieldValue('whetherInclude')
      if (whetherFinance === '1' || whetherInclude === '1') {
        iamRule = '0'
      } else {
        if (this.secUnitflag != null && !this.secUnitflag) {
          iamRule = '1'
        }
        if (this.secUnitflag) {
          iamRule = '2'
        }
      }

      this.$refs.docform.setFieldValue('iamRule', iamRule)
    },

    auditRule() {
      let iamRule = ''
      const whetherInclude = this.$refs.docform.getFieldValue('whetherInclude')
      const whetherFinance = this.$refs.docform.getFieldValue('whetherFinance')
      const whetherLeave = this.$refs.docform.getFieldValue('whetherLeave')
      // if (whetherLeave === '1') {
      //   iamRule = '3'
      // }
      // if (whetherFinance === '1' || whetherInclude === '1') {
      //   iamRule = '0'
      // }
      if (whetherFinance === '1' || whetherInclude === '1') {
        iamRule = '0'
      } else {
        if (this.secUnitflag != null && !this.secUnitflag) {
          iamRule = '1'
        }
      }

      // if (whetherLeave === '1') {
      //   iamRule = '3'
      // } else
      if (whetherFinance === '1' || whetherInclude === '1') {
        iamRule = '0'
      } else {
        if (this.secUnitflag) {
          iamRule = '2'
        }
      }

      this.$refs.docform.setFieldValue('iamRule', iamRule)
    },
    getOrgId(model) {
      var targetDeptMember = model.targetDeptMember
      var code = targetDeptMember[0].code
      this.$refs.docform.setFieldValue('orgId', code)
    },
    targetDeptMemberChange1(targetDeptMember) {
      var code = targetDeptMember[0].code
      if (code !== null && code !== '') {
        axios({
          url: 'api/xcoa-mobile/v1/iamtarget/checkGroup?code=' + code,
          method: 'get',
        }).then((res) => {
          this.secUnitflag = res.data
          this.auditRule()
        })
      } else {
        this.secUnitflag = null
        this.auditRule()
      }
    },
    targetDeptMemberChange(model) {
      debugger
      var targetDeptMember = model.targetDeptMember
      if (targetDeptMember.length > 0) {
        var code = targetDeptMember[0].code
        axios({
          url: 'api/xcoa-mobile/v1/iamtarget/analysisRegisterAddress?code=' + code,
          method: 'get',
        }).then((res) => {
          this.$refs.docform.setFieldValue('country', res.data.country)
          this.$refs.docform.setFieldValue('region', res.data.region)
          this.$refs.docform.setFieldValue('registerAddress', res.data.registerAddress)
          this.$refs.docform.setFieldValue('simple', res.data.abbreviation)
        })
        this.$refs.docform.setFieldValue('orgId', code)
        axios({
          url: 'api/xcoa-mobile/v1/iamtarget/checkGroup?code=' + code,
          method: 'get',
        }).then((res) => {
          this.secUnitflag = res.data
          this.auditRule()
        })
      } else {
        this.secUnitflag = null
        this.auditRule()
      }
    },
    showModal() {
      this.visible = true
    },
    Selected(keys, keyinfos) {
      this.visible = false
      if (keyinfos?.length > 0) {
        this.$refs.docform.setFieldValue('orgName', keyinfos[0].orgName)
        this.$refs.docform.setFieldValue('orgId', keyinfos[0].orgId)
      }
    },
    getCheckNode(checkNode) {
      this.visible = false
    },
    changeNum(data) {
      data.forEach((item, index) => {
        item.sortNum = index + 1
      })
    },
    handleChange(model, event) {
      model.label = event.join('、')
      this.labelArray = [...event]
    },
    handelPublish() {},
    saveForm() {
      var orgId = this.$refs.docform.getFieldValue('orgId')
      var id = this.$route.query.id ? this.$route.query.id : null
      if (orgId) {
        axios({
          url: 'api/xcoa-mobile/v1/iamtarget/validate?id=' + id + '&orgId=' + orgId,
          method: 'get',
        }).then((res) => {
          if (res.status === 200) {
            if (res.data) {
              this.$refs.docform.saveBtnClick()
            } else {
              Message.error('该机构已存在', 1)
            }
          }
        })
      }
    },
    saved() {
      Message.success({ content: '保存成功！' }).then(() => {
        this.close(true)
      })
    },
    initParam(val) {
      setTimeout(() => {
        var flow = this.$refs.docform
        if (
          flow.getFieldValue('parentId') === null ||
          flow.getFieldValue('parentId') === undefined ||
          flow.getFieldValue('parentId') === ''
        ) {
          if (this.$route.query?.typeId) {
            this.$refs.docform.setFieldValue('parentId', this.$route.query.typeId)
          }
        }
      }, 0)
      return true
    },
    close(flag) {
      crossWindowWatcher.notifyChange(this.$route.path, flag)
      window.close()
    },
    validForm() {
      return new Promise((resolve, reject) => {
        resolve(true)
      })
    },
    getFormSelectFieldValue(value) {
      let result = ''
      if (value !== undefined) {
        const resultArry = this.iamRuleOptions.filter((e) => {
          return e.id === value
        })
        if (resultArry.length > 0) {
          result = resultArry[0].name
        }
      }
      return result
    },
  },
}
</script>

<style module lang="scss">
@import '@/webflow/sd-flow-form.scss';

.ant-card-body {
  padding: 12px;

  :global(.buttons_sd-detail-form_common) {
    :global(.ant-form-item-control-wrapper) {
      padding-top: 4%;
      padding-left: 24%;
    }
  }

  .tr_border {
    box-sizing: border-box;
    border-right: 1px solid #e8e8e8;
    border-left: 1px solid #e8e8e8;
  }

  :global(.title_sd-detail-form_common) {
    font-size: 1.5em;
    text-align: center;
  }
}

.form {
  :global .iamtargetform > td.ant-form-item-label > label {
    width: 160px;
    white-space: break-spaces !important;
  }
}
</style>
