<template>
  <span>
    <audit-advanced-query
      :expand="expand"
      :search-data="formData"
      :ref-name="searchform"
      :search-style="{ height: '170px', left: '0px', top: '40px' }"
      :search-fun="handleSearch"
      @searchedClick="searchedClick"
    >
      <template>
        <a-col :span="12">
          <a-form-model-item :label="'审计问题标题'" prop="findTitle">
            <a-input v-model="formData.findTitle" allow-clear />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item :label="'审计问题编号'" prop="findCode">
            <a-input v-model="formData.findCode" allow-clear />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item :label="'审计问题描述'" prop="findDesc">
            <a-input v-model="formData.findDesc" allow-clear />
          </a-form-model-item>
        </a-col>
        <!-- <a-col :span="12">
          <a-form-model-item :label="'审计建议描述'" prop="suggestion">
            <a-input v-model="formData.suggestion" allow-clear />
          </a-form-model-item>
        </a-col> -->
      </template>
    </audit-advanced-query>
    <div :class="[$style.btns]">
      <audit-advanced-export
        ref="sjzlExport"
        :class-style="[$style.buttonSpacing]"
        :exclebxh="false"
        :expressions="expressions"
        :config-id="271"
        :v-if="false"
      />
    </div>
    <div :class="[$style.btns]">
      <audit-advanced-import
        ref="sjzlImport"
        :config-id="'171'"
        :table-id="'sjzlTable'"
        :relevant-column="relevant"
        :v-if="false"
        @importfromfileAfter="importfromfileAfter"
      >
      </audit-advanced-import>
    </div>
    <sd-data-table-ex
      ref="sjzlTable"
      form-id="iamAuditReportFind"
      page-id="audit/work/reportFind/spicAuditReportFind"
      show-selection
      :filter-expressions="expressions"
      :data-url="dataurl1"
      :columns="columns"
      :actions="actions"
      :search-fields="['findTitle']"
      :show-advance-query="true"
      :modal-props="{ class: 'noBottom' }"
      @searchbtnClick="searchbtnClick"
    >
      <div slot="islink" slot-scope="text, record">
        <a :title="text" @click="rowClick(record)">{{ text }}</a>
      </div>
      <div slot="attachment" slot-scope="text">
        <sd-attachment
          :group-id="JSON.parse(text).value ? JSON.parse(text).value : text"
          read-only
        />
      </div>
      <template slot="findType" slot-scope="text">
        {{ JSON.parse(text).text }}
      </template>
    </sd-data-table-ex>
    <!-- 选择审计步骤模板 -->
    <a-modal
      title="请选择审计问题"
      width="1200px"
      :visible="showFindVisible"
      :confirm-loading="findConfirmLoading"
      destroy-on-close
      @ok="handleOk"
      @cancel="
        () => {
          showFindVisible = false
        }
      "
    >
      <sd-data-table-ex
        ref="findTable"
        data-url="api/xcoa-mobile/v1/audit-fact-confirm/list"
        form-id="iamAuditDiscover"
        :columns="findListColumns"
        :row-key="'findTitle'"
        :filter-expressions="findExpressions"
        show-selection
      >
        <template slot="findType" slot-scope="text">
          {{ JSON.parse(text).text }}
        </template>
      </sd-data-table-ex>
    </a-modal>
  </span>
</template>

<script>
import { message } from 'ant-design-vue'
import TableActionTypes from '@/common/services/table-action-types'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import axios from '@/common/services/axios-instance'
import { getUserInfo } from '@/common/store-mixin'
import auditAdvancedImport from '../../../../components/audit-advanced-import.vue'
import auditAdvancedExport from '../../../../components/audit-advanced-export.vue'
import auditAdvancedQuery from '../../../../components/audit-advanced-query.vue'
import auditAdvancedQueryMixins from '../../../../components/audit-advanced-query-mixins'
import components from './_import-components/xm-audit-find-list-import'

export default {
  name: 'XmAuditFindList',
  metaInfo: {
    title: '审计建议及风险',
  },
  components: {
    ...components,
    auditAdvancedQuery,
    auditAdvancedExport,
    auditAdvancedImport,
  },
  mixins: [auditAdvancedQueryMixins],
  data() {
    return {
      projectId: this.$root.$route.query.projectId,
      relevant: this.$root.$route.query.projectId * 1,
      searchform: 'searchform',
      expressions: [
        {
          dataType: 'long',
          name: 'projectId',
          op: 'eq',
          longValue: this.$root.$route.query.projectId,
        },
      ],
      formData: {
        materialTitle: '',
        materialCode: '',
        docStatus: null,
        creationTime: null,
      },
      columns: [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: '名称',
          dataIndex: 'findTitle',
          scopedSlots: { customRender: 'islink' },
          width: '15%',
        },
        {
          title: '编号',
          dataIndex: 'findCode',
          width: '15%',
          sorter: true,
        },
        {
          title: '问题类别',
          dataIndex: 'problemType',
          width: '15%',
          scopedSlots: { customRender: 'problemType' },
          sdHidden: true,
        },
        // {
        //   title: '问题分类',
        //   dataIndex: 'problemCategoryFunction',
        //   width: '20%',
        //   customRender: (text, record, index) => JSON.parse(text).text,
        //   sdHidden: true,
        // },
        {
          title: '性质',
          dataIndex: 'problemNature',
          width: '10%',
          scopedSlots: { customRender: 'problemNature' },
        },
        {
          title: '发送整改状态',
          dataIndex: 'sendStatus',
          width: '130px',
          sorter: true,
          sdHidden: true,
        },
        {
          title: '编制人员',
          dataIndex: 'creatorName',
          width: '120px',
          sorter: true,
        },
      ],
      actions: [],
      dataurl1: 'api/xcoa-mobile/v1/audit-report-find/all-two-list',
      showFindVisible: false,
      findConfirmLoading: false,
      findListColumns: [
        {
          title: '问题名称（定性描述）',
          dataIndex: 'findTitle',
        },
        {
          title: '审计问题编号',
          dataIndex: 'findCode',
        },
        {
          title: '审计问题类别',
          dataIndex: 'problemType',
          scopedSlots: { customRender: 'problemType' },
          sdHidden: true,
        },
        {
          title: '被审计单位',
          dataIndex: 'auditedUnitNames',
        },
        // {
        //   title: '问题分类',
        //   dataIndex: 'problemCategoryFunction',
        // },
        {
          title: '审计性质',
          dataIndex: 'problemNature',
          scopedSlots: { customRender: 'problemNature' },
        },
        {
          title: '确认状态',
          dataIndex: 'confirmsStatus',
        },
        {
          title: '编制人员',
          dataIndex: 'creatorName',
        },
      ],
      findExpressions: [
        {
          dataType: 'long',
          name: 'projectId',
          op: 'eq',
          longValue: this.$root.$route.query.projectId,
        },
        {
          dataType: 'str',
          name: 'confirmsStatus',
          op: 'eq',
          stringValue: '02',
        },
        {
          dataType: 'long',
          name: 'reportChoose',
          op: 'eq',
          longValue: 0,
        },
      ],
    }
  },
  mounted() {
    this.isShowBtn()
  },
  methods: {
    // 查看当前登录人是否项目成员，如果同时是项目阅读人员，取最大权限（项目成员权限）
    inProjectUser(userList) {
      var isProjectUser = false
      userList.map((item) => {
        if (item.userAccount === getUserInfo().account) {
          isProjectUser = true
          return isProjectUser
        }
      })
      return isProjectUser
    },
    isShowBtn() {
      const projectId = this.$root.$route.query.projectId
      axios({
        url: `api/xcoa-mobile/v1/iamauditproject/getProjectInfoById?id=` + projectId,
        method: 'get',
      }).then((res) => {
        if (res.data) {
          const itemStatus = res.data.itemStatus
          const readAuthorityCodes = res.data.readAuthorityCodes
          const userList = res.data.iamProjectUserList
          var isProjectUser = this.inProjectUser(userList)
          if (['05', '06', '07'].includes(itemStatus)) {
            this.actions.push({
              label: '导出',
              id: 'export',
              permission: null,
              callback: () => {
                this.$refs.sjzlExport.exportdata()
              },
            })
          } else {
            if (
              readAuthorityCodes != null &&
              readAuthorityCodes.indexOf(getUserInfo().account) > -1 &&
              !isProjectUser
            ) {
              this.actions = []
            } else {
              this.actions = [
                {
                  label: '删除',
                  id: 'delete',
                  permission: 'delete',
                  type: TableActionTypes.ex.delete,
                },
                {
                  label: '新建',
                  id: 'new',
                  type: TableActionTypes.primary,
                  // 新建按钮，不需要回调，自动处理
                  permission: 'iamAuditMaterial-create', // 权限控制
                  callback: () => {
                    const url = '/xm-audit-report-find-form?projectId=' + this.projectId // 新页面要打开的路由地址
                    crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
                      if (refreshFlag) {
                        // 这里写或者调刷新的方法
                        this.refresh()
                      }
                    })
                    // window.open('#/sd-flow-guide?code=AUDIT_MATERIAL&projectId=' + this.projectId)
                  },
                },
                {
                  label: '导出',
                  id: 'export',
                  permission: null,
                  callback: () => {
                    this.$refs.sjzlExport.exportdata()
                  },
                },
                {
                  label: '导入',
                  id: 'importExcel', // 按钮id
                  permission: 'create', // 有创建的权限才能导入
                  callback: () => {
                    this.$refs.sjzlImport.showImportPanel()
                    // message.success('导入成功!')
                    //  this.refresh()
                  },
                },
              ]
            }
          }
        }
      })
    },
    handleOk() {
      const selectInfo = this.$refs.findTable.getSelectedRows()
      if (selectInfo.length) {
        const arr = []
        selectInfo.forEach((item) => {
          arr.push(item.id)
        })
        this.findConfirmLoading = true
        axios
          .get(`api/xcoa-mobile/v1/audit-report-find/find-save?ids=${arr.join(',')}`)
          .then((res) => {
            if (res.data.code === 200) {
              this.showFindVisible = false
              this.findConfirmLoading = false
              message.success('添加成功!')
              this.$refs.sjzlTable.refresh()
            }
          })
      } else {
        message.error('请选择审计发现!')
        return false
      }
    },
    importfromfileAfter() {
      this.$refs.sjzlTable.refresh()
      // this.refresh()
    },
    // 刷新列表
    refresh() {
      this.$refs.sjzlTable.refresh()
    },
    // 新建、详情打开新页面
    rowClick(record) {
      // debugger
      const projectStatus = this.$root.$route.query.projectStatus
      const sendStatus = record.sendStatus
      if (sendStatus === '已发送') {
        const url =
          '/xm-audit-report-find-form?record=' +
          record.id +
          '&projectId=' +
          this.projectId +
          '&edit=false' // 新页面要打开的路由地址
        crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
          if (refreshFlag) {
            this.refresh()
          }
        })
      } else {
        const url =
          '/xm-audit-report-find-form?record=' +
          record.id +
          '&projectId=' +
          this.projectId +
          '&projectStatus=' +
          projectStatus // 新页面要打开的路由地址
        crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
          if (refreshFlag) {
            this.refresh()
          }
        })
      }
    },
    // 查询
    handleSearch() {
      // 默认查询条件
      this.expressions = [
        {
          dataType: 'long',
          name: 'projectId',
          op: 'eq',
          longValue: this.$root.$route.query.projectId,
        },
      ]

      // 审计发现标题
      if (this.formData.findTitle) {
        this.expressions.push({
          dataType: 'str',
          name: 'findTitle',
          op: 'like',
          stringValue: `%${this.formData.findTitle}%`,
        })
      }

      // 审计发现编号
      if (this.formData.findCode) {
        this.expressions.push({
          dataType: 'str',
          name: 'findCode',
          op: 'like',
          stringValue: `%${this.formData.findCode}%`,
        })
      }

      // 审计发现描述
      if (this.formData.findDesc) {
        this.expressions.push({
          dataType: 'str',
          name: 'findDesc',
          op: 'like',
          stringValue: `%${this.formData.findDesc}%`,
        })
      }

      // 审计建议描述
      // if (this.formData.suggestion) {
      //   this.expressions.push({
      //     dataType: 'str',
      //     name: 'suggestion',
      //     op: 'like',
      //     stringValue: `%${this.formData.suggestion}%`,
      //   })
      // }
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.buttonSpacing {
  margin-left: 5px;
}
.btns {
  position: absolute;
  top: 24px;
  right: 99.5px;
  z-index: 100;
}
</style>
