<template>
  <a-spin :spinning="!inited">
    <sd-detail-form
      ref="form"
      v-sd-watermark="waterMark"
      page-id="audit/project/iamAuditProject"
      form-id="iamAuditProject"
      :record-id="this.$route.query.projectId ? parseInt(this.$route.query.projectId) : null"
      :class="$style.form"
      :read-only="!editable"
      @close="close(true)"
      @saved="saved"
      @modifyLogCustomData="modifyLogCustomData"
      @sdFormReady="
        () => {
          this.initData()
        }
      "
    >
      <template v-slot="{ model, fields }">
        <table>
          <tr>
            <td style="padding-left:5px;border:none">
              <audit-advanced-group
                :expand="projectinfoExpand"
                :expand-str="'projectinfoExpand'"
                :group-label="'变更项目信息'"
                tablestyle="''"
                @changedClick="changedClick"
              ></audit-advanced-group>
            </td>
          </tr>
        </table>

        <table v-show="projectinfoExpand">
          <tr>
            <sd-form-item-td name="projectTitle" :colspan="3" />
            <sd-form-item-td name="auditType" :colspan="3">
              <span>{{ fields.auditType.attr.displayValue }}</span>
            </sd-form-item-td>
          </tr>
          <tr class="bklabeloverflow">
            <sd-form-item-td name="projectPrincipalId" label="项目负责人" :colspan="3">
              <sd-user-picker
                v-model="model.projectPrincipalId"
                :single="true"
                :read-only="false"
                @change="projectPrincipalChange"
              />
            </sd-form-item-td>
            <sd-form-item-td name="projectCode" :colspan="3">
              <span>{{ model.projectCode }}</span>
            </sd-form-item-td>
          </tr>
          <tr>
            <sd-form-item-td name="auditedUnitIds" :colspan="7" />
            <!-- <sd-form-item-td name="auditBasis" /> -->
          </tr>
          <tr>
            <sd-form-item-td name="auditMode" :colspan="3" />
            <sd-form-item-td
              v-if="model.auditType === '03' || model.auditType === '04'"
              name="auditedUser"
              :colspan="3"
            ></sd-form-item-td>
          </tr>
          <tr>
            <sd-form-item-td v-if="model.auditMode === '02'" name="externalUnitIds" :colspan="3">
              <template v-slot:read-and-edit="{ editable }">
                <AuditGroupPicker
                  v-if="editable"
                  v-model="model.externalUnitIds"
                  :read-only="false"
                  :selectclick="showselectexternal"
                />
                <span v-else>{{ model.externalUnitNames }}</span>
              </template>
            </sd-form-item-td>
          </tr>
          <tr>
            <sd-form-item-td name="projectContent" :colspan="7">
              <a-textarea v-model="model.projectContent" :rows="3" />
            </sd-form-item-td>
          </tr>
          <tr>
            <sd-form-item-td name="whetherFinance" :colspan="3" hidden="true" />
            <sd-form-item-td name="whetherOverseas" :colspan="3" hidden="true" />
          </tr>
          <tr class="auditprojectdetailname">
            <sd-form-item-td name="whetherAuditCoverage" :colspan="3" />
          </tr>
          <!-- <tr>
            <sd-form-item-td name="auditObjective" :colspan="3">
              <a-textarea v-model="model.auditObjective" :rows="3" />
            </sd-form-item-td>
          </tr> -->
          <tr>
            <sd-form-item-td name="planStartTime" :colspan="3" />
            <sd-form-item-td name="planEndTime" :colspan="3" />
          </tr>
          <tr>
            <sd-form-item-td name="planDays" :colspan="6"></sd-form-item-td>
          </tr>
          <tr>
            <sd-form-item-td name="groupLeaderId" :colspan="6">
              <sd-user-picker v-model="model.groupLeaderId" :single="true" :read-only="true" />
            </sd-form-item-td>
            <!-- <sd-form-item-td name="projectSource" component="a-select"></sd-form-item-td> -->
          </tr>
          <tr>
            <sd-form-item-td name="exPersonnelNum" :colspan="3" hidden="true">
              <a-input-number v-model="model.exPersonnelNum" style="width: 100%;"></a-input-number>
            </sd-form-item-td>
            <sd-form-item-td name="predictedCost" :colspan="3" hidden="true">
              <a-input-number
                v-model="model.predictedCost"
                :min="0"
                :precision="2"
                style="width: 100%;"
              ></a-input-number>
            </sd-form-item-td>
          </tr>
          <tr>
            <sd-form-item-td name="auditProcess" :colspan="3">
              <template v-slot:read-and-edit="{ editable }">
                <!-- <sd-select
                  v-if="editable"
                  v-model="model.auditProcess"
                  :options="auditProcessOptions"
                /> -->
                <span>{{ JSON.parse(model.auditProcess)[0].name }}</span>
              </template>
            </sd-form-item-td>
            <sd-form-item-td name="linkmanIds" :label="'被审计单位联系人'" :colspan="3" />
          </tr>
          <tr class="bklabeloverflow">
            <sd-form-item-td
              :name="['auditperiodStart', 'auditperiodEnd']"
              :colspan="3"
              :input-props="[{ placeholder: '开始' }, { placeholder: '结束' }]"
              :label="'审计期间'"
            />
            <sd-form-item-td name="auditAssets" :colspan="3">
              <a-input-number
                v-model="model.auditAssets"
                :min="0"
                :precision="2"
                style="width: 100%;"
              ></a-input-number>
            </sd-form-item-td>
          </tr>
          <!-- <tr>
            <sd-form-item-td name="overseas" />
            <sd-form-item-td name="auditAssets">
              <a-input-number
                v-model="model.auditAssets"
                :min="0"
                :precision="2"
                style="width: 100%;"
              ></a-input-number>
            </sd-form-item-td>
          </tr> -->
          <tr>
            <sd-form-item-td name="auditDomains" :colspan="3" hidden="true">
              <a-checkbox-group v-model="model.auditDomains">
                <a-checkbox
                  v-for="(item, index) in fields.auditDomains.attr.selectListItem"
                  :key="index"
                  :value="item.value"
                >
                  {{ item.label }}
                </a-checkbox>
              </a-checkbox-group>
            </sd-form-item-td>
            <sd-form-item-td name="readAuthorityIds" :label="'项目阅读权限范围'" :colspan="3" />
          </tr>
          <tr>
            <sd-form-item-td name="attachment" :colspan="6">
              <template v-slot:read-and-edit="{ editable }">
                <sd-attachment
                  v-model="model.attachment"
                  :group-id="JSON.parse(fields.attachment.value).value"
                  :read-only="!editable"
                />
              </template>
            </sd-form-item-td>
          </tr>
          <tr>
            <sd-form-item-td name="projectRemarks" :colspan="7">
              <a-textarea v-model="model.projectRemarks" :rows="3" />
            </sd-form-item-td>
          </tr>
          <tr v-if="editable">
            <td style="margin-top: 20px;text-align: center;border:none" :colspan="8">
              <a-button type="primary" @click="saveForm">保存</a-button>
            </td>
          </tr>
        </table>

        <table v-if="initParam(model)">
          <tr>
            <td style="padding-left:5px; border:none">
              <audit-advanced-group
                :expand="projectchange"
                :expand-str="'projectchange'"
                :group-label="'项目变更记录'"
                tablestyle="''"
                @changedClick="changedClick"
              ></audit-advanced-group>
            </td>
          </tr>
        </table>

        <table
          v-for="(bg, index) in modifyLogs"
          v-show="projectchange"
          :key="index"
          :class="$style.tablexm"
        >
          <tr>
            <td style="width:160px;text-align:right;vertical-align:top">{{ bg.creatorName }}</td>
            <td colspan="3">
              <div
                style="
    width: 18px;margin-left:2px;
    font-size: 8px;
    color: #fff;
    text-align:center;
    background-color: lightgreen;
    border-radius: 100%;
"
                >√
              </div>
              <div style="padding-left:10px;margin-left:9px;border-left:1px solid gray"
                >{{ bg.creationTime | sdDateFormat('YYYY-MM-DD HH:mm:ss') }}
                <table>
                  <tr v-for="(x, index) in bg.xx" :key="index">
                    <td style="white-space: nowrap;"
                      >[{{ x.fieldName === 'linkmanIds' ? '被审计单位联系人' : x.fieldDesc }}]</td
                    >
                    <td
                      >{{ x.oldValue !== '' ? '"' : ''
                      }}{{
                        x.oldValue.indexOf('[') !== -1 ||
                        x.oldValue.indexOf('{') !== -1 ||
                        x.newValue.indexOf('[') !== -1 ||
                        x.newValue.indexOf('{') !== -1
                          ? ''
                          : x.oldValue === 'null'
                          ? ''
                          : x.oldValue
                      }}{{ x.oldValue !== '' ? '" 改为 ' : ''
                      }}<span v-if="x.oldValue === ''" style="color:green">
                        {{
                          x.newValue.indexOf('[') !== -1 || x.newValue.indexOf('{') !== -1
                            ? '修改动态表格数据'
                            : x.newValue
                        }}</span
                      >
                      <span v-else>{{
                        x.newValue.indexOf('[') !== -1 || x.newValue.indexOf('{') !== -1
                          ? '修改动态表格数据'
                          : '"' + x.newValue + '"'
                      }}</span>
                    </td>
                  </tr>
                </table>
              </div>
            </td>
          </tr>
        </table>

        <!-- <table v-if="initParam(model)">
          <tr>
            <td :colspan="4">
              <audit-advanced-group :group-label="'项目变更记录'">
                <template>
                  <table style="margin-top:50px;width:100%">
                    <tr>
                      <td>
                        <span>
                          <div
                            v-for="action in modifyLogs"
                            :key="action.creationTime + action.creatorName"
                          >
                            <div>
                              <sd-user-item
                                :users="[{ code: action.creatorAccount, name: action.creatorName }]"
                              ></sd-user-item>
                              <span>{{
                                action.creationTime | sdDateFormat('YYYY-MM-DD HH:mm:ss')
                              }}</span>
                            </div>
                            <div
                              v-for="item in action.details"
                              :key="item.id"
                              style="padding-left:50px"
                            >
                              <template>
                                <span>[{{ item.fieldDesc }}]</span>
                                <template v-if="item.oldValue !== null">
                                  <span class="oldVal"
                                    ><template
                                      v-if="
                                        item.fieldName === 'joinEndTime' ||
                                          item.fieldName === 'joinStartTime'
                                      "
                                    >
                                      {{ parseInt(item.oldValue, 10) | sdDateFormat('YYYY-MM-DD') }}
                                    </template>
                                    <template v-else-if="item.fieldName === 'userType'">
                                      {{ getUserType(item.oldValue) }}
                                    </template>
                                    <template v-else-if="item.fieldName === 'userId'">
                                      <sd-user-item :users="JSON.parse(item.oldValue)"></sd-user-item>
                                    </template>
                                    <template v-else-if="item.fieldName === 'auditProcess'">
                                      {{ getAuditProcess(item.oldValue) }}
                                    </template>
                                    <template v-else>
                                      {{ item.oldValue }}
                                    </template></span
                                  >改为</template
                                >
                                <span class="newVal">
                                  <template
                                    v-if="
                                      item.fieldName === 'joinEndTime' ||
                                        item.fieldName === 'joinStartTime'
                                    "
                                    >{{
                                      parseInt(item.newValue, 10) | sdDateFormat('YYYY-MM-DD')
                                    }}</template
                                  >
                                  <template v-else-if="item.fieldName === 'userType'">
                                    {{ getUserType(item.newValue) }}
                                  </template>
                                  <template v-else-if="item.fieldName === 'userId'">
                                    <sd-user-item :users="JSON.parse(item.newValue)"></sd-user-item>
                                  </template>
                                  <template v-else-if="item.fieldName === 'auditProcess'">
                                    {{ getAuditProcess(item.newValue) }}
                                  </template>
                                  <template v-else>
                                    {{ item.newValue }}
                                  </template>
                                </span>
                              </template>
                            </div>
                          </div>
                        </span>
                      </td>
                    </tr>
                  </table>
                </template>
              </audit-advanced-group>
            </td>
          </tr>
        </table> -->

        <a-modal
          :visible="modalvisible"
          title="请选择"
          width="1200px"
          :body-style="{
            padding: 0,
            minHeight: '700px',
          }"
          :destroy-on-close="true"
          @ok="handleOk"
          @cancel="handleCancel"
        >
          <sd-data-table-ex
            ref="externalTable"
            check-type="checkbox"
            :filter-expressions="expressions"
            :columns="modalcolumns"
            form-id="iamExternalBase"
            page-id="audit/auditsource/extrnal/iamExternalBase"
            :search-fields="['name', 'code', 'address']"
            show-selection
          >
          </sd-data-table-ex>
        </a-modal>
      </template>
    </sd-detail-form>
  </a-spin>
</template>

<script>
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import axios from '@/common/services/axios-instance'
import { Message, Modal } from 'ant-design-vue'
import systemManage from '@/system-manage/system-manage'
import auditProjectchangeService from '@product/iam/audit/work/projectchange/audit-projectchange-service'
import TableColumnTypes from '@/common/services/table-column-types'
import AuditGroupPicker from '../../../components/picker/audit-group-picker.vue'
import auditAdvancedGroup from '../../../components/audit-advanced-group.vue'
import auditAdvancedGroupMixins from '../../../components/audit-advanced-group-mixins'
import xmChildTableMixins from '../../../components/xm-child-table-mixins'
import components from './_import-components/audit-projectchange-form-import'

export default {
  name: 'AuditProjectChangeForm',
  metaInfo: {
    title: '项目变更',
  },
  components: {
    ...components,
    auditAdvancedGroup,
    AuditGroupPicker,
  },
  mixins: [auditAdvancedGroupMixins, xmChildTableMixins],
  data() {
    return {
      inited: true,
      waterMark: systemManage.getFormWaterMark(),
      projectinfoExpand: true,
      projectchangeInfoExpand: true,
      projectId: '',
      projectStatus: '',
      modifyLogs: [],
      editable: false,
      modalvisible: false,
      auditProcessOptions: [],
      modalcolumns: [
        {
          title: '序号',
          dataIndex: 'sortNumber',
          width: '80px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        {
          dataIndex: 'id',
          sdHidden: true,
        },
        {
          title: '企业名称',
          dataIndex: 'name',
          // sdClickable: true, // 列内容是否可点击
          scopedSlots: { customRender: 'islink' },
        },
        {
          title: '类型',
          dataIndex: 'category',
          width: '160px',
        },
        {
          title: '统一社会信用代码',
          dataIndex: 'code',
          width: '180px',
        },
        {
          title: '住所',
          dataIndex: 'address',
          width: '70px',
        },
        {
          title: '企业状态',
          sorter: true,
          dataIndex: 'status',
          width: '100px',
        },
        {
          title: '当前参与项目',
          dataIndex: 'joinProject',
          width: '150px',
          scopedSlots: { customRender: 'isProject' },
        },
        {
          title: '编制人员',
          dataIndex: 'authName',
          width: '100px',
        },
        {
          title: '编制日期',
          dataIndex: 'authTime',
          sorter: true,
          defaultSortOrder: 'descend',
          sdRender: TableColumnTypes.date,
        },
      ],
      expressions: [],
      externalUnitIds: [],
      projectchange: true,
      dataWhenLoadAtts: '',
    }
  },
  created() {
    const projectId = this.$route.query.projectId
    const projectStatus = this.$route.query.projectStatus
    if (projectId) {
      this.projectId = projectId
    }
    if (projectStatus) {
      this.projectStatus = projectStatus
    }
  },
  mounted() {
    auditProjectchangeService.checkOperatorAuthority(this.projectId).then((res) => {
      if (res.status === 200) {
        this.editable = res.data
      }
      if (this.projectStatus === '05' || this.projectStatus === '07') {
        this.editable = false
      }
    })
    // 初始化数据字典信息
    this.initDictionaryInfo()
    this.loadChangeInfo()
  },
  methods: {
    getAuditProcess(val) {
      if (val.substr(0, 1) === '[') {
        return JSON.parse(val)[0].name
      } else {
        return val
      }
    },
    initDictionaryInfo() {
      // 获取审计流程下拉框信息
      axios({
        url: 'api/xcoa-mobile/v1/iamauditproject/getProjectProcessList?projectId=' + this.projectId,
        method: 'get',
      }).then((res) => {
        if (res.status === 200) {
          this.auditProcessOptions = res.data
        }
      })
    },
    projectPrincipalChange(val) {
      if (val.length > 0) {
        const userList = this.$refs.form.getFieldValue('iamProjectUserList')
        userList.forEach((item) => {
          if (item.userType === '04') {
            const resultDataArry = []
            resultDataArry.push({
              type: 'User',
              code: val[0].code,
              name: val[0].name,
            })
            item.userId = JSON.stringify(resultDataArry)
            item.userAccount = val[0].code
            item.userName = val[0].name
          }
        })
        this.$refs.form.setFieldValue('iamProjectUserList', userList)
      }
    },
    loadChangeInfo() {
      auditProjectchangeService.getUserChangeLogInfo(this.projectId).then((res) => {
        if (res.data) {
          const modifyLogs = []
          res.data
            .sort(function(a, b) {
              return b.creationTime - a.creationTime
            })
            .forEach((item) => {
              if (item.fieldName !== 'iamProjectUserList') {
                item.xt = item.creatorName + '_' + item.creationTime
                const i = modifyLogs.find((n) => n.xt === item.xt)
                if (item.newValue === null) {
                  item.newValue = ''
                }
                if (item.oldValue === null) {
                  item.oldValue = ''
                }
                if (i !== undefined) {
                  i.xx.push({
                    fieldDesc: item.fieldDesc,
                    fieldName: item.fieldName,
                    newValue: item.newValue,
                    oldValue: item.oldValue,
                  })
                } else {
                  item.xx = [
                    {
                      fieldDesc: item.fieldDesc,
                      fieldName: item.fieldName,
                      newValue: item.newValue,
                      oldValue: item.oldValue,
                    },
                  ]
                  modifyLogs.push(item)
                }
                // if (
                //   modifyLogs[modifyLogs.length - 1] &&
                //   modifyLogs[modifyLogs.length - 1].creatorName === item.creatorName &&
                //   modifyLogs[modifyLogs.length - 1].creationTime === item.creationTime
                // ) {
                //   modifyLogs[modifyLogs.length - 1].details.push(item)
                // } else {
                //   modifyLogs[modifyLogs.length] = {
                //     beanId: item.beanId,
                //     creationTime: item.creationTime,
                //     creatorAccount: item.creatorAccount,
                //     creatorName: item.creatorName,
                //     details: [item],
                //   }
                // }
              }
            })
          this.modifyLogs = modifyLogs
        }
      })
    },
    close(flag) {
      crossWindowWatcher.notifyChange(this.$route.fullPath, flag)
      window.close()
    },
    saved() {
      this.inited = true
      Message.success('保存成功', 1).then((res) => {
        this.loadChangeInfo()
        this.$refs.form.resetWatchField()
        this.updateAuditYear()
      })
    },
    updateAuditYear() {
      axios({
        url: 'api/xcoa-mobile/v1/iamauditproject/updateAuditYear?id=' + this.projectId,
        method: 'get',
      })
    },
    // 保存
    saveForm() {
      this.inited = false
      this.$refs.form.saveBtnClick()
    },
    // 展示选择列表
    showselectexternal() {
      this.modalvisible = !this.modalvisible
    },
    // 弹出窗确认
    handleOk() {
      this.showselectexternal()
      // 获取别选择的行信息
      const selectInfo = this.$refs.externalTable.getSelectedRows()
      const list = []
      selectInfo.forEach((item) => {
        const obj = {
          title: item.name,
          id: item.code,
          code: item.code,
          name: item.name,
          text: item.name,
          type: 'Group',
          props: {},
        }
        list.push(obj)
      })
      this.$refs.form.setFieldValue('externalUnitIds', list)
    },
    // 弹出窗取消
    handleCancel() {
      this.showselectexternal()
    },
    initData() {
      if (this.externalUnitIds.length > 0) {
        this.$refs.form.setFieldValue('externalUnitIds', this.externalUnitIds)
      }
    },
    initParam(model) {
      const list = []
      let codes = []
      let names = []
      const externalUnitCodes = model.externalUnitCodes
      const externalUnitNames = model.externalUnitNames
      if (externalUnitCodes) {
        codes = externalUnitCodes.split(',')
        names = externalUnitNames.split(',')
        for (let i = 0; i < codes.length; i++) {
          const obj = {
            title: names[i],
            id: codes[i],
            code: codes[i],
            name: names[i],
            text: names[i],
            type: 'Group',
            props: {},
          }
          list.push(obj)
        }
        this.externalUnitIds = list
      }
      this.initAtts(model)
      return true
    }, // 更新保存修改记录的json
    modifyLogCustomData(modifyLogData) {
      // 判断如果是附件，则重新计算附件的变更记录
      modifyLogData.forEach((res, index) => {
        if (res.key === 'attachment') {
          // 这里重新计算附件的value
          var dataWhenSave = this.$refs.form.getBackendValues()
          dataWhenSave.forEach((res) => {
            if (res.name === 'attachment') {
              var attachments = this.$refs.form.getFieldValue(res.name)
              var attnames = this.getAttachmentsValue(attachments)
              if (this.dataWhenLoadAtts !== attnames) {
                res.oldVal = this.dataWhenLoadAtts
                res.newVal = attnames
              } else {
                modifyLogData.splice(index, 1)
              }
            }
          })
        }
      })
      return modifyLogData
    },
    initAtts(mode) {
      if (this.dataWhenLoadAtts === '') {
        this.dataWhenLoadAtts = this.getAttachmentsValue(mode.attachment)
      }
    },
    getAttachmentsValue(attachments) {
      var value = []
      for (var i = 0; i < attachments.length; i++) {
        value.push(attachments[i].name)
      }
      return value.join('，')
    },
  },
}
</script>

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

:global(.title_sd-detail-form_common) {
  visibility: hidden;
}

.form {
  :global(.buttons_sd-detail-form_common) {
    visibility: hidden;
  }
}

.tablexm tr td {
  border: none !important;
}
</style>
