<template>
  <div :class="$style.wrapHeight">
    <!-- 高级搜索区域 -->
    <audit-advanced-query
      :expand="expand"
      :search-data="SJBGAdvSearchForm"
      :ref-name="searchform"
      :search-style="{ height: '135px', left: '0px', top: '50px' }"
      :search-fun="advSJBGSearch"
      @searchedClick="searchedClick"
    >
      <template>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="被审计单位" prop="auditedUnitNames">
              <a-input v-model="SJBGAdvSearchForm.auditedUnitNames" />
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="12">
            <a-form-model-item label="报告类型" prop="reportType">
              <sd-select
                v-model="SJBGAdvSearchForm.reportType"
                :allow-clear="true"
                :options="auditTypeOptions"
              />
            </a-form-model-item>
          </a-col> -->
        </a-row>
      </template>
    </audit-advanced-query>
    <sd-data-table-ex
      ref="SJBGDataTable"
      :filter-expressions="SJBGTableExpressions"
      :columns="columns1"
      show-selection
      form-id="iamAuditReport"
      page-id="audit/work/report/iamAuditReport"
      :data-url="dataurl1"
      :actions="actions1"
      :show-advance-query="true"
      :search-fields="['fileTitle']"
      :modal-props="{ class: 'noBottom' }"
      @searchbtnClick="searchbtnClick"
    >
      <div slot="isLink" slot-scope="text, record">
        <a :title="text" @click="showProjectDetail(record)">{{ text }}</a>
      </div>
    </sd-data-table-ex>
  </div>
</template>

<script>
import { getUserInfo } from '@/common/store-mixin'
import TableColumnTypes from '@/common/services/table-column-types'
import TableActionTypes from '@/common/services/table-action-types'
import { message, Modal } from 'ant-design-vue'
import axios from '@/common/services/axios-instance'
import errorUtil from '@/common/services/error-util'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import auditProjectchangeService from '@product/iam/audit/work/projectchange/audit-projectchange-service'
import auditAdvancedQuery from '../../../../components/audit-advanced-query.vue'
import auditAdvancedQueryMixins from '../../../../components/audit-advanced-query-mixins'
import AuditService from './iam-audit-report-service'
import components from './_import-components/iam-audit-report-list-import'

export default {
  name: 'IamAuditReportList',
  metaInfo: {
    title: '审计报告',
  },
  components: { ...components, auditAdvancedQuery },
  mixins: [auditAdvancedQueryMixins],
  data() {
    return {
      expand: false,
      expanded: false,
      projectId: this.$route.query.projectId,
      activeKey: '1',
      auditTypeOptions: [],
      searchform: 'searchform',
      isShowAdvSearch: false,
      SJBGAdvSearchForm: {
        auditedUnitNames: '',
        reportType: '',
      },
      SJBGTableExpressions: [
        {
          dataType: 'long',
          name: 'projectId',
          op: 'eq',
          longValue: this.$route.query.projectId,
        },
      ],
      BasicTableExpressions: [
        {
          dataType: 'long',
          name: 'projectId',
          op: 'eq',
          longValue: this.$route.query.projectId,
        },
      ],
      pageId: 'audit/work/report/iamAuditReport',
      dataurl1: 'api/xcoa-mobile/v1/iam-audit-report/all-list',
      columns1: [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: '报告名称',
          dataIndex: 'fileTitle',
          width: '30%',
          scopedSlots: { customRender: 'isLink' },
        },
        {
          title: '被审计单位',
          dataIndex: 'auditedUnitNames',
        },
        {
          title: '文件编号',
          dataIndex: 'fileCode',
          sorter: true,
        },
        {
          title: '报告类型',
          dataIndex: 'reportType',
          sorter: true,
          width: '150px',
        },
        {
          title: '编制人员',
          dataIndex: 'drawUpName',
          width: '120px',
        },
        {
          title: '编制日期',
          dataIndex: 'drawUpTime',
          defaultSortOrder: 'descend',
          sortDirections: 'descend',
          sdRender: TableColumnTypes.date,
          width: '120px',
        },
        {
          title: '当前状态',
          dataIndex: 'flowState',
        },
        {
          title: '当前处理人',
          dataIndex: 'currentUser',
          // customRender: (text, record, index) => `${record.CURRENT_USER}`,
        },
        {
          title: '当前环节号',
          dataIndex: 'endType',
          sdHidden: true,
        },
        // {
        //   title: 'instId',
        //   dataIndex: 'instId',
        //   sdHidden: true,
        // },

        // {
        //   title: 'FLOWINSTANCEID',
        //   dataIndex: 'FLOWINSTANCEID',
        //   sdHidden: true,
        // },
        // {
        //   title: 'projectId',
        //   dataIndex: 'projectId',
        //   sdHidden: true,
        // },
      ],
      actions1: [],
      // actions1: [
      //   {
      //     label: '删除',
      //     id: 'delete',
      //     permission: null,
      //     type: TableActionTypes.ex.delete,
      //     callback: () => {
      //       const url = '/sd-flow-guide?code=IAM_AUDIT_REPORT&projectId=' + this.projectId // 新页面要打开的路由地址
      //       crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
      //         if (refreshFlag) {
      //           // 这里写或者调刷新的方法
      //           this.refresh()
      //         }
      //       })
      //     },
      //   },
      //   {
      //     label: '新建',
      //     id: 'new',
      //     type: TableActionTypes.primary, // 新建按钮，不需要回调，自动处理
      //     permission: null, // 权限控制
      //     callback: () => {
      //       this.createAuditReport()
      //     },
      //   },
      // ],
      columns2: [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: '项目名称',
          width: '250px',
          dataIndex: 'projectTitle',
          scopedSlots: { customRender: 'isLink' },
        },
        {
          title: '项目编号',
          dataIndex: 'projectCode',
        },
        {
          title: '变更类型',
          dataIndex: 'changeType',
          sorter: true,
        },
        {
          title: '编制人员',
          dataIndex: 'creatorName',
          sorter: true,
        },
        {
          title: '编制日期',
          dataIndex: 'creationTime',
          sorter: true,
          sdRender: TableColumnTypes.date,
        },
        {
          title: '当前状态',
          sorter: true,
          dataIndex: 'flowState',
        },
        {
          title: '当前环节号',
          dataIndex: 'endType',
          sdHidden: true,
        },
        {
          title: '当前处理人',
          dataIndex: 'currentUser',
        },
      ],
      actions2: [],
      columns3: [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: '计划年度',
          dataIndex: 'planYear',
          sorter: true,
          scopedSlots: { customRender: 'isLink' },
        },
        {
          title: '审计机构',
          sorter: true,
          dataIndex: 'unitName',
        },
        {
          title: '编制人员',
          dataIndex: 'creatorName',
        },
        {
          title: '编制日期',
          dataIndex: 'creationTime',
          sdRender: TableColumnTypes.date,
        },
        {
          title: '当前状态',
          sorter: true,
          dataIndex: 'flowState',
        },
        {
          title: '结束发布标记',
          hidden: true,
          sorter: true,
          dataIndex: 'endType',
          sdHidden: true,
        },
        {
          title: '当前环节号',
          dataIndex: 'endType',
          sdHidden: true,
        },
        {
          title: '当前处理人',
          dataIndex: 'currentUser',
        },
      ],
      actions3: [],
      formId: 'iamAuditReport',
      tableId: 'SJBGDataTable',
      itemStatusOptions: [],

      auditModeOptions: [],
      changeTypeOptions: [],
      showOpinionModal: false,
      pending: [],
      batchSubmitSucceed: [],
      batchsubmitFailed: [],
      form: {
        opinion: '',
        groupId: '',
      },
    }
  },
  mounted() {
    AuditService.getDictionary('REPORT_TYPE').then((res) => {
      this.auditTypeOptions = res.data
    })
    auditProjectchangeService.checkOperatorAuthority(this.projectId).then((res) => {
      if (res.status === 200) {
        if (!res.data) {
          this.actions1 = []
        } else {
          this.actions1 = [
            {
              label: '删除',
              id: 'delete',
              permission: null,
              type: TableActionTypes.ex.delete,
              callback: () => {
                const url = '/sd-flow-guide?code=PRODUCT_IAM_SJBG&projectId=' + this.projectId // 新页面要打开的路由地址
                crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
                  if (refreshFlag) {
                    // 这里写或者调刷新的方法
                    this.refresh()
                  }
                })
              },
            },
            {
              label: '新建',
              id: 'new',
              type: TableActionTypes.primary, // 新建按钮，不需要回调，自动处理
              permission: null, // 权限控制
              callback: () => {
                this.createAuditReport()
              },
            },
          ]
        }
      }
    })
    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.actions1 = []
          } else {
            // if (
            //   readAuthorityCodes != null &&
            //   readAuthorityCodes.indexOf(getUserInfo().account) > -1 &&
            //   !isProjectUser
            // ) {
            //   this.actions = []
            // } else {
            //   this.actions1 = [
            //     {
            //       label: '删除',
            //       id: 'delete',
            //       permission: null,
            //       type: TableActionTypes.ex.delete,
            //       callback: () => {
            //         const url = '/sd-flow-guide?code=PRODUCT_IAM_SJBG&projectId=' + this.projectId // 新页面要打开的路由地址
            //         crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
            //           if (refreshFlag) {
            //             // 这里写或者调刷新的方法
            //             this.refresh()
            //           }
            //         })
            //       },
            //     },
            //     {
            //       label: '新建',
            //       id: 'new',
            //       type: TableActionTypes.primary, // 新建按钮，不需要回调，自动处理
            //       permission: null, // 权限控制
            //       callback: () => {
            //         this.createAuditReport()
            //       },
            //     },
            //   ]
            // }
          }
        }
      })
    },
    // 刷新列表
    refresh() {
      this.$refs.SJBGDataTable.refresh()
    },
    // 创建审计计划
    createAuditReport() {
      const reporttype = '02'
      const selectRows = this.$refs.SJBGDataTable.getSelectedRows()
      // let promise = new Promise()
      if (selectRows.length !== 0) {
        const record = selectRows[0]
        const params = {
          inputs: [
            { name: 'formId', value: record.formId },
            { name: 'beanId', value: record.beanId },
            { name: 'flowId', value: record.flowId },
            { name: 'advancedFields', value: '' },
            { name: 'attFields', value: 'reportAttachment,attachment' },
          ],
          pagePath: '/audit/work/report/iamAuditReport',
          ignoreFieldValue:
            'fileTitle,fileCode,reportNumber,issueDate,auditedUnit,auditedUnitIds,auditedUnitNames,reportType,attachment,drawUpName,drawUpAccount,drawUpTime',
        }
        AuditService.copyReport(params).then((res) => {
          this.showProjectDetail({
            flowState: null,
            currentUser: getUserInfo().name,
            instId: res.data.instId,
          })
        })
      } else {
        const url = '/sd-flow-guide?code=PRODUCT_IAM_SJBG&projectId=' + this.projectId // 新页面要打开的路由地址
        // const url =
        //   '/sd-flow-guide?code=PRODUCT_IAM_SJBG&projectId=' +
        //   this.projectId +
        //   '&reportType=' +
        //   reporttype // 新页面要打开的路由地址
        crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
          if (refreshFlag) {
            // 这里写或者调刷新的方法
            this.refresh()
          }
        })
      }
    },
    editProject(id) {
      // 校验项目是否已启动
      AuditService.checkProjectIsStart(id).then((res) => {
        if (res.data) {
          Modal.warning({
            title: '提示',
            content: '该项目已启动!',
          })
          return null
        } else {
          window.open(`#/sd-flow-guide?code=PRODUCT_IAM_SJJHBG&oper=edit&projectId=${id}`)
        }
      })
    },
    toggleTabs(key) {
      this.activeKey = key
      if (this.activeKey === '1') {
        this.tableId = 'SJXMDataTable'
        // 初始化年份下拉框
        this.initYearSelect()
      }
      if (this.activeKey === '2') {
        this.tableId = 'SJXMDataTable'
      }
      if (this.activeKey === '3') {
        this.tableId = 'SJJHDataTable'
      }
      this.$refs[`${this.tableId}`].clearSelection()
      this.$refs[`${this.tableId}`].refresh()
    },
    linkToDelete() {
      if (this.activeKey === '1') {
        this.tableId = 'SJXMDataTable'
        this.formId = 'iamAuditProject'
      }
      if (this.activeKey === '2') {
        this.tableId = 'SJXMDataTable'
        this.formId = 'iamAuditProject'
      }
      if (this.activeKey === '3') {
        this.tableId = 'SJJHDataTable'
        this.formId = 'iamAuditPlan'
      }
      const selectedRowKeys = this.$refs[`${this.tableId}`].getSelectedRowKeys()
      if (selectedRowKeys.length === 0) {
        Modal.info({
          content: '请选择需要删除的数据！',
        })
        return
      }
      if (this.activeKey === '3') {
        AuditService.beforeDeleteCheck(selectedRowKeys).then((res) => {
          // 删除前校验
          if (res.data) {
            Modal.warning({
              title: '提示',
              content: '存在已启动项目请删除，当前需要先物理删除已启动项目，再删除《审计计划》!',
            })
            return null
          } else {
            return new Promise((resolve) => {
              Modal.confirm({
                title: '您确定删除这项内容吗？',
                content: '删除这条数据后，就无法恢复初始的状态。',
                okText: '删除',
                okType: 'danger',
                onOk: () => {
                  axios({
                    url: 'api/xcoa-mobile/v1/page/' + this.formId,
                    method: 'delete',
                    params: {
                      ids: selectedRowKeys.join(','),
                    },
                  })
                    .then(() => {
                      const msg = '删除成功'
                      message.success(msg)
                      this.$refs[`${this.tableId}`].clearSelection()
                      this.$refs[`${this.tableId}`].refresh()
                    })
                    .catch((err) => {
                      const msg = errorUtil.getMessage(err) || '删除失败'
                      message.error(msg)
                    })
                    .finally(resolve)
                },
                onCancel: () => {
                  resolve()
                },
              })
            })
          }
        })
      } else {
        return new Promise((resolve) => {
          Modal.confirm({
            title: '您确定删除这项内容吗？',
            content: '删除这条数据后，就无法恢复初始的状态。',
            okText: '删除',
            okType: 'danger',
            onOk: () => {
              axios({
                url: 'api/xcoa-mobile/v1/page/' + this.formId,
                method: 'delete',
                params: {
                  ids: selectedRowKeys.join(','),
                },
              })
                .then(() => {
                  const msg = '删除成功'
                  message.success(msg)
                  this.$refs[`${this.tableId}`].clearSelection()
                  this.$refs[`${this.tableId}`].refresh()
                })
                .catch((err) => {
                  const msg = errorUtil.getMessage(err) || '删除失败'
                  message.error(msg)
                })
                .finally(resolve)
            },
            onCancel: () => {
              resolve()
            },
          })
        })
      }
    },
    AdvSearchClick() {
      this.isShowAdvSearch = !this.isShowAdvSearch
    },
    searchedClick() {
      this.expand = !this.expand
    },
    onSearch(value) {
      if (this.activeKey === '1') {
        this.SJBGTableExpressions = this.BasicTableExpressions
        if (value) {
          const expressions = []
          // 被审计单位
          expressions.push({
            dataType: 'str',
            name: 'auditedUnitNames',
            op: 'like',
            stringValue: `%${value}%`,
          })
          // 报告类型
          // expressions.push({
          //   dataType: 'str',
          //   name: 'reportType',
          //   op: 'like',
          //   stringValue: `%${value}%`,
          // })
          this.SJBGTableExpressions.push({
            dataType: 'exps',
            op: 'or',
            expressionsValue: expressions,
          })
        }
      }
    },
    advSJBGSearch() {
      this.SJBGTableExpressions = []
      const expressions = []
      this.BasicTableExpressions.forEach((item) => {
        this.SJBGTableExpressions.push(item)
      })
      // 报告类型
      // if (
      //   this.SJBGAdvSearchForm.reportType &&
      //   this.SJBGAdvSearchForm.reportType[0] &&
      //   this.SJBGAdvSearchForm.reportType[0] !== ''
      // ) {
      //   expressions.push({
      //     dataType: 'str',
      //     name: 'reportType',
      //     op: 'eq',
      //     stringValue: this.SJBGAdvSearchForm.reportType[0].id,
      //   })
      // }

      // 被审计单位
      if (this.SJBGAdvSearchForm.auditedUnitNames) {
        expressions.push({
          dataType: 'str',
          name: 'auditedUnitNames',
          op: 'like',
          stringValue: `%${this.SJBGAdvSearchForm.auditedUnitNames}%`,
        })
      }
      if (expressions.length !== 0) {
        this.SJBGTableExpressions.push({
          dataType: 'exps',
          op: 'and',
          expressionsValue: expressions,
        })
      }
      this.isShowAdvSearch = false
    },
    showProjectDetail(record) {
      let openurl = ''
      const loginUser = getUserInfo()
      if (record.endType === 0) {
        if (loginUser.name === record.currentUser) {
          openurl = '/sd-webflow/pages/draft/' + record.instId
        } else {
          openurl = '/sd-webflow/done-pages/' + record.instId
        }
      } else {
        openurl = '/sd-webflow/done-pages/' + record.instId
      }
      crossWindowWatcher.waitForChanged(openurl).then((refreshFlag) => {
        if (refreshFlag) {
          // 这里写或者调刷新的方法
          this.refresh()
        }
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
</style>
