<template>
  <a-card>
    <!-- 高级搜索区域 -->
    <audit-advanced-query
      :expand="expand"
      :class="$style.advancedQuery"
      :search-data="advSearchForm"
      :ref-name="searchform"
      :search-style="{ height: '260px', left: '0px', top: '50px' }"
      :search-fun="advSearch"
      @searchedClick="searchedClick"
      @resetForm="resetForm"
    >
      <template>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="问题名称" prop="findingTitle">
              <a-input v-model="advSearchForm.findingTitle" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="问题编号" prop="findingCode">
              <a-input v-model="advSearchForm.findingCode" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-model-item :label="'项目名称'" prop="projectName">
              <a-input v-model="advSearchForm.projectName" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="销号状态" prop="cancellStatus">
              <sd-select
                v-model="advSearchForm.cancellStatus"
                :allow-clear="true"
                :options="cancellStatusOptions"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="整改责任主体" prop="auditedUnit">
              <sd-group-picker
                ref="unitSelect"
                v-model="advSearchForm.auditedUnit"
                :single="true"
                :read-only="false"
                @change="changeunit"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="整改责任主体联系人" prop="auditedContacts">
              <sd-user-picker
                ref="userSelect"
                v-model="advSearchForm.auditedContacts"
                :hierarchical="false"
                :single="true"
                :read-only="false"
                @change="changeauditedContacts"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="计划年度" prop="planYear">
              <a-date-picker
                v-model="advSearchForm.planYear"
                mode="year"
                picker="YYYY"
                format="YYYY"
                :allow-clear="false"
                placeholder="选择年度"
                :input-read-only="true"
                :value="year"
                :open="endOpen"
                @panelChange="yearChange"
                @openChange="handleEndOpenChange"
              ></a-date-picker>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item :label="'整改状态'" prop="rectStatus">
              <sd-select
                v-model="advSearchForm.rectStatus"
                :allow-clear="true"
                :options="StatusOptions"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
      </template>
    </audit-advanced-query>
    <div :class="$style.rectPlanProjectlist">
      <sd-data-table-ex
        ref="dataTable"
        :projectlist="true"
        :class="$style.rectfeedbacklist"
        :columns="columns"
        :actions="actions"
        show-selection
        form-id="spicRectFeedback"
        data-url="api/xcoa-mobile/v1/spicrectfeedback/list"
        :filter-expressions="tableExpressions"
        :show-advance-query="true"
        :search-fields="['findingTitle']"
        :custom-delete-fun="deleteRows"
        @searchbtnClick="searchbtnClick"
      >
        <div slot="isLink" slot-scope="text, record">
          <a :title="text" @click="linkFindingtitle(record)">{{ text }}</a>
        </div>
      </sd-data-table-ex>
    </div>
  </a-card>
</template>

<script>
import axios from '@/common/services/axios-instance'
import { message, Modal } from 'ant-design-vue'
import errorUtil from '@/common/services/error-util'
import { getUserInfo } from '@/common/store-mixin'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import auditAdvancedQuery from '@product/iam/components/audit-advanced-query.vue'
import auditAdvancedQueryMixins from '@product/iam/components/audit-advanced-query-mixins'
import components from './_import-components/spic-rectfeedback-list-import'

export default {
  name: 'SpicRectfeedbackList',
  metaInfo: {
    title: '整改反馈',
  },
  components: { ...components, auditAdvancedQuery },
  mixins: [auditAdvancedQueryMixins],
  data() {
    return {
      endOpen: false,
      year: null,
      searchYear: '',
      yearArry: [],
      searchValue: '',
      mainSendUnit: [],
      checkboxValue: false,
      pageId: 'audit/spicrectfeedback/spicRectFeedback',
      columns: [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: 'id',
          dataIndex: 'id',
          sdHidden: true,
        },
        {
          title: '问题名称（定性描述）',
          dataIndex: 'findingTitle',
          width: '300px',
          scopedSlots: { customRender: 'isLink' },
        },

        {
          title: '问题编号',
          dataIndex: 'findingCode',
          sorter: true,
          width: '200px',
          // sortDirections: ['ascend', 'descend'],
        },
        {
          title: '项目名称',
          dataIndex: 'projectName',
          width: '300px',
        },
        {
          title: '计划年度',
          dataIndex: 'planYear',
          width: '100px',
        },
        {
          title: '整改责任主体',
          dataIndex: 'auditedUnitName',
          width: '150px',
        },
        {
          title: '整改责任主体联系人',
          dataIndex: 'auditedContactsName',
          width: '150px',
          // sdHidden: true,
        },
        {
          title: '整改责任部门',
          dataIndex: 'responsibleDeptName',
          width: '150px',
        },
        {
          title: '问题性质',
          dataIndex: 'problemNature',
          width: '100px',
        },
        {
          title: '问题分类',
          dataIndex: 'problemCategoryFunction',
          width: '180px',
        },
        // {
        //   title: '整改责任主体',
        //   dataIndex: 'auditedUnitName',
        //   sorter: true,
        //   width: '150px',
        //   sortDirections: ['ascend', 'descend'],
        // },
        {
          title: '整改类型',
          dataIndex: 'rectType',
          width: '150px',
        },
        {
          title: '整改状态',
          dataIndex: 'rectState',
          width: '150px',
        },
        {
          title: '销号状态',
          dataIndex: 'cancellStatus',
          width: '150px',
        },
        {
          dataIndex: 'auditedContactsAccount',
          sdHidden: true,
        },
        // {
        //   title: '操作',
        //   dataIndex: 'id',
        //   scopedSlots: { customRender: 'opt' },
        //   width: '100px',
        // },
        {
          title: '操作',
          dataIndex: 'opt',
          aligen: 'center',
          customRender: (text, record, index) => {
            if (
              record.problemNature === '问题类' &&
              record.auditedContactsAccount === getUserInfo().account
            ) {
              return (
                <span>
                  <a vOn:click={(evt) => this.delayApply(record)}>延期申请</a>
                </span>
              )
            }
          },
          width: '100px',
        },
        {
          title: '流程ID',
          dataIndex: 'instId',
          sdHidden: true,
        },
      ],
      actions: [
        // {
        //   label: '新建',
        //   id: 'new',
        //   type: TableActionTypes.primary, // 新建按钮，不需要回调，自动处理
        //   permission: null, // 纯前端操作，不需要权限控制
        //   callback: this.createrectfeedback,
        // },
        // {
        //   label: '删除',
        //   id: 'delete',
        //   type: TableActionTypes.ex.delete, // 删除按钮，不需要回调，会自动处理（对sd-data-table无效）
        // },
        // {
        //   label: '删除',
        //   id: 'delete',
        //   type: 'delete', // 删除按钮，不需要回调，会自动处理（对sd-data-table无效）
        //   permission: null,
        // },
        // {
        //   label: '导出',
        //   permission: null, // 纯前端操作，不需要权限控制
        //   callback: () => {
        //     this.$refs.exportExcel.exportdata()
        //   },
        // },
      ],
      tableExpressions: [],
      buttonsfortable: [
        // {
        //   label: '变更',
        //   id: 'changeleader',
        //   showCondition: '',
        // },
      ],
      searchform: 'searchform',
      expand: false,
      advSearchForm: {
        findingTitle: '',
        findingCode: '',
        cancellStatus: '',
        projectName: '',
        planYear: '',
        auditedUnit: '',
        auditedContacts: '',
        rectStatus: [],
      },
      StatusOptions: [],
      cancellStatusOptions: [],
      projectId: '',
      setType: '',
      unitName: '',
      contactsName: '',
    }
  },
  mounted() {
    // 初始化数据字典信息
    this.initDictionaryInfo()
  },
  methods: {
    yearChange(value) {
      this.year = value
      this.advSearchForm.planYear = value.format('YYYY')
      if (document.getElementsByClassName('ant-calendar-picker-container').length > 0) {
        document.getElementsByClassName('ant-calendar-picker-container')[0].style.display = 'none'
      }
    },
    changeunit(values) {
      this.unitName = ''
      values.forEach((element) => {
        this.unitName = element.name
      })
    },
    changeauditedContacts(values) {
      this.contactsName = ''
      values.forEach((element) => {
        this.contactsName = element.name
      })
      console.log('---------------', this.contactsName)
    },

    handleEndOpenChange(open) {
      this.endOpen = open
    },
    // 整改延期
    delayApply(record) {
      axios({
        url:
          `api/xcoa-mobile/v1/spicRectifyQuestionDelay/enable-status?rectFeedbackId=` + record.id,
        method: 'get',
      }).then((res) => {
        if (res.data) {
          Modal.info({
            content: '延期申请未结束',
          })
        } else {
          const url = `/sd-flow-guide?code=SPIC_RECT_DELAY&rectFeedbackId=${record.id}&projectId=${record.projectId}`
          crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
            if (refreshFlag) {
              this.refresh()
            }
          })
        }
      })
    },
    initDictionaryInfo() {
      axios({
        url: 'api/xcoa-mobile/v1/iam-law/dictionary?key=RECT_STATUS',
        method: 'get',
      }).then((res) => {
        this.StatusOptions = res.data.map((val) => {
          return {
            id: val.id,
            name: val.name,
          }
        })
      })
      axios({
        url: 'api/xcoa-mobile/v1/iam-law/dictionary?key=CANCELL_STATUS',
        method: 'get',
      }).then((res) => {
        if (res.status === 200) {
          this.cancellStatusOptions = res.data
        }
      })
    },

    createrectfeedback() {
      // 审计问题反馈
      // const url = `/sd-flow-guide?code=SPIC_AUDIT_WTFK` // 新页面要打开的路由地址
      // 审计风险反馈
      const url = `/sd-flow-guide?code=SPIC_AUDIT_FXFK`
      // 审计建议反馈
      // const url = `/sd-flow-guide?code=SPIC_AUDIT_JYFK`
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          this.$refs.dataTable.refresh()
        }
      })
    },

    onSearch(value) {
      this.tableExpressions = []
      if (value) {
        const expressions = []
        // 问题名称
        expressions.push({
          dataType: 'str',
          name: 'findingTitle',
          op: 'like',
          stringValue: `%${value}%`,
        })
        // 问题编号
        expressions.push({
          dataType: 'str',
          name: 'findingCode',
          op: 'like',
          stringValue: `%${value}%`,
        })
        this.tableExpressions.push({
          dataType: 'exps',
          op: 'or',
          expressionsValue: expressions,
        })
        // 项目名称
        expressions.push({
          dataType: 'str',
          name: 'projectName',
          op: 'like',
          stringValue: `%${value}%`,
        })
      }
    },

    advSearch() {
      this.tableExpressions = []
      // 问题名称
      if (this.advSearchForm.findingTitle) {
        this.tableExpressions.push({
          dataType: 'str',
          name: 'findingTitle',
          op: 'like',
          stringValue: `%${this.advSearchForm.findingTitle}%`,
        })
      }
      // 问题编号
      if (this.advSearchForm.findingCode) {
        this.tableExpressions.push({
          dataType: 'str',
          name: 'findingCode',
          op: 'like',
          stringValue: `%${this.advSearchForm.findingCode}%`,
        })
      }

      // 整改状态
      if (this.advSearchForm.cancellStatus.length > 0) {
        this.tableExpressions.push({
          dataType: 'str',
          name: 'cancellStatus',
          op: 'like',
          stringValue: `%${this.advSearchForm.cancellStatus[0].id}%`,
        })
      }
      // 项目名称
      if (this.advSearchForm.projectName) {
        this.tableExpressions.push({
          dataType: 'str',
          name: 'projectName',
          op: 'like',
          stringValue: `%${this.advSearchForm.projectName}%`,
        })
      }
      // 年度计划
      if (this.advSearchForm.planYear) {
        this.tableExpressions.push({
          dataType: 'str',
          name: 'planYear',
          op: 'eq',
          stringValue: `${this.advSearchForm.planYear}`,
        })
      }
      // 整改责任主体
      if (this.advSearchForm.auditedUnit) {
        this.tableExpressions.push({
          dataType: 'str',
          name: 'auditedUnitName',
          op: 'like',
          stringValue: `%${this.unitName}%`,
        })
      }
      // 整改责任主体联系人
      if (this.advSearchForm.auditedContacts) {
        this.tableExpressions.push({
          dataType: 'str',
          name: 'auditedContactsName',
          op: 'like',
          stringValue: `%${this.contactsName}%`,
        })
      }
      console.log('aaaaaaaaaaaaaaaa')
      // 整改状态
      if (this.advSearchForm.rectStatus.length > 0) {
        this.tableExpressions.push({
          dataType: 'str',
          name: 'RECT_STATE',
          op: 'eq',
          stringValue: `${this.advSearchForm.rectStatus[0].id}`,
        })
      }
    },
    searchedClick() {
      this.expand = !this.expand
    },
    // 重置年份
    resetForm() {
      this.advSearchForm.auditedUnit = ''
      this.advSearchForm.auditedContacts = ''
      this.unitName = ''
      this.advSearchForm.cancellStatus = []
      this.advSearchForm.rectStatus = []
    },
    deleteRows() {
      const selectedRowKeys = this.$refs.dataTable.getSelectedRowKeys()
      if (selectedRowKeys.length === 0) {
        Modal.info({
          content: '请选择需要删除的文件',
        })
        return
      }

      const selectedRows = this.$refs.dataTable.getSelectedRows()
      let flag = false
      selectedRows.forEach((item) => {
        if (item.endType !== '0') {
          flag = true
        }
      })
      if (flag) {
        Modal.error({
          title: '删除失败：存在不是草稿状态的数据',
        })
        return
      }
      return new Promise((resolve) => {
        Modal.confirm({
          title: '您确定删除这项内容吗？',
          content: '删除这条数据后，就无法恢复初始的状态。',
          okText: '删除',
          cancelText: '取消',
          okType: 'danger',
          onOk: () => {
            axios({
              url: 'api/framework/v1/page/' + this.$refs.dataTable.formId,
              method: 'delete',
              params: { ids: selectedRowKeys.join(',') },
            })
              .then(() => {
                this.$refs.dataTable.clearSelection()
                this.$refs.dataTable.refresh()
                message.success('删除成功')
                this.$emit('recordsDeleted', selectedRowKeys)
              })
              .catch((err) => {
                const msg = errorUtil.getMessage(err) || '删除失败'
                message.error(msg)
              })
              .finally(resolve)
          },
          onCancel: () => {
            resolve()
          },
        })
      })
    },

    linkFindingtitle(record) {
      // debugger
      window.open('#/sd-webflow/done-pages/' + record.instId)
    },
    AdvSearchClick() {
      this.expand = !this.expand
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.advancedQuery {
  :global(.ant-col .ant-form-item-label) {
    width: 20% !important;
  }

  :global(.ant-col .ant-form-item-control-wrapper) {
    width: 80% !important;
  }
}
</style>
