<template>
  <!-- <div class="auditsqapplylist"> -->
  <div>
    <a-card>
      <a-radio-group v-model="radioValue" allow-clear @change="radioOnChange">
        <a-radio :value="1">
          全部
        </a-radio>
        <a-radio :value="2">
          待处理
        </a-radio>
      </a-radio-group>
      <!-- 高级搜索组件 -->
      <audit-advanced-query
        :expand="expand"
        :search-data="formData"
        :ref-name="searchform"
        :search-style="{ height: '180px', left: '20px', top: '80px' }"
        :search-fun="handleSearch"
        @searchedClick="searchedClick"
      >
        <template>
          <a-col :span="12">
            <a-form-model-item :label="'报送单位'" prop="submitUnitName">
              <a-input v-model="formData.submitUnitName" allow-clear />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item :label="'报送人'" prop="submitUserName">
              <a-input v-model="formData.submitUserName" allow-clear />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item :label="'报送月份'" prop="submitMonth">
              <a-select
                v-model="formData.submitMonth"
                :options="monthOptions"
                allow-clear
              ></a-select>
            </a-form-model-item>
            <!-- <a-form-model-item :label="'报送月份'" prop="submitMonth">
              <a-input v-model="formData.submitMonth" allow-clear />
            </a-form-model-item> -->
          </a-col>
          <a-col :span="12">
            <a-form-model-item :label="'报送时间'" prop="submitDate">
              <a-range-picker v-model="formData.submitDate" />
            </a-form-model-item>
          </a-col>
        </template>
      </audit-advanced-query>
      <!-- <a-form-model>
        <a-row :gutter="24">
          <a-button type="primary" @click="projectExport">
            查询
          </a-button>
        </a-row>
      </a-form-model> -->

      <sd-data-table-ex
        ref="projectFDataTable"
        :filter-expressions="expressions"
        :columns="columns"
        :actions="actions"
        form-id="spicEngineConstruceBase"
        data-url="api/xcoa-mobile/v1/spicengineconstrucebase/dataList"
        :search-fields="['submitUnitName', 'submitMonth', 'submitUserName']"
        show-selection
        :show-advance-query="true"
        @searchbtnClick="searchbtnClick"
      >
        <template slot="islink" slot-scope="text, record">
          <a :title="text" @click="rowClick(record)">{{ text }}</a>
        </template>
      </sd-data-table-ex>
    </a-card>
  </div>
</template>

<script>
import download from '@/common/services/download'
import axios from '@/common/services/axios-instance'
import PageService from '@/common/services/page-service'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import TableColumnTypes from '@/common/services/table-column-types'
import TableActionTypes from '@/common/services/table-action-types'
import { getUserInfo } from '@/common/store-mixin'
import { message, Modal } from 'ant-design-vue'
import auditAdvancedQueryMixins from '@product/iam/components/audit-advanced-query-mixins'
import auditAdvancedGroupMixins from '@product/iam/components/audit-advanced-group-mixins'
import auditAdvancedQuery from '@product/iam/components/audit-advanced-query.vue'
import components from './_import-components/spic-engine-construce-base-import'

export default {
  name: 'SpicEngineConstruceBase',
  metaInfo: {
    title: '工程建设项目',
  },
  components: {
    ...components,
    auditAdvancedQuery,
  },
  mixins: [auditAdvancedQueryMixins, auditAdvancedGroupMixins],
  data() {
    return {
      isCreateProject: true,
      radioValue: 1,
      expressions: [],
      searchform: 'searchform',
      formId: 'spicEngineConstruceBase',
      formData: {
        submitMonth: '',
        submitUnitName: '',
        submitUserName: '',
        submitDate: '',
      },
      monthOptions: [
        { value: '1', label: '1月' },
        { value: '2', label: '2月' },
        { value: '3', label: '3月' },
        { value: '4', label: '4月' },
        { value: '5', label: '5月' },
        { value: '6', label: '6月' },
        { value: '7', label: '7月' },
        { value: '8', label: '8月' },
        { value: '9', label: '9月' },
        { value: '10', label: '10月' },
        { value: '11', label: '11月' },
        { value: '12', label: '12月' },
      ],
      columns: [
        {
          title: '报送单位',
          dataIndex: 'submitUnitName',
        },
        {
          title: '报送月份',
          dataIndex: 'submitMonth',
          scopedSlots: { customRender: 'islink' },
        },
        {
          title: 'instId',
          dataIndex: 'instId',
          sdHidden: true,
        },
        {
          title: '报送人',
          dataIndex: 'submitUserName',
        },
        {
          title: '报送时间',
          dataIndex: 'submitDate',
          sdRender: TableColumnTypes.date,
        },
        {
          title: 'instId',
          dataIndex: 'instId',
          sdHidden: true,
        },
        {
          title: '当前状态',
          dataIndex: 'flowState',
        },
        {
          title: '当前处理人',
          dataIndex: 'currentUser',
        },
      ],
      actions: [
        {
          label: '新建',
          id: 'new',
          permission: 'create',
          type: TableActionTypes.primary,
          callback: () => {
            const url = '/sd-flow-guide?code=SPIC_AUDIT_GCJSXM' // 新页面要打开的路由地址
            crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
              if (refreshFlag) {
                // 这里写或者调刷新的方法
                this.refreshDataTable()
              }
            })
          },
        },
        {
          label: '删除',
          id: 'delete',
          permission: null,
          type: TableActionTypes.batch,
          callback: this.deleteRows,
          // type: TableActionTypes.ex.delete, // 删除按钮，不需要回调，会自动处理（对sd-data-table无效）
        },
        {
          label: '导出',
          permission: null, // 纯前端操作，不需要权限控制
          callback: () => {
            this.projectExport()
          },
        },
      ],
    }
  },
  methods: {
    // 判断数组或字符串为null或长度为0
    strOrArr(strOrArr) {
      return strOrArr !== null && strOrArr.length > 0
    },
    projectExport() {
      debugger
      this.expressions = []
      if (this.radioValue === 1) {
        this.expressions.push({
          dataType: 'str',
          name: 'stateFlag',
          op: 'eq',
          stringValue: 'true',
        })
      } else if (this.radioValue === 2) {
        this.expressions.push({
          dataType: 'str',
          name: 'stateFlag',
          op: 'eq',
          stringValue: 'false',
        })
      }
      // 报送单位
      if (this.formData.submitUnitName) {
        this.expressions.push({
          dataType: 'str',
          name: 'submitUnitName',
          op: 'like',
          stringValue: `${this.formData.submitUnitName}`,
        })
      }
      // 报送月份
      if (this.formData.submitMonth) {
        this.expressions.push({
          dataType: 'str',
          name: 'submitMonth',
          op: 'eq',
          stringValue: `${this.formData.submitMonth}`,
        })
      }
      // 报送人
      if (this.formData.submitUserName) {
        this.expressions.push({
          dataType: 'str',
          name: 'submitUserName',
          op: 'like',
          stringValue: `${this.formData.submitUserName}`,
        })
      }
      // 报送时间
      if (this.strOrArr(this.formData.submitDate)) {
        if (this.formData.submitDate[0] === null || this.formData.submitDate[0] === '') {
          this.formData.submitDate = null
        } else {
          this.expressions.push({
            dataType: 'str',
            name: 'submitDate',
            op: 'ge',
            stringValue: `${this.formData.submitDate[0].format('YYYY-MM-DD')}`,
          })
          this.expressions.push({
            dataType: 'str',
            name: 'submitDate',
            op: 'le',
            stringValue: `${this.formData.submitDate[1].format('YYYY-MM-DD')}`,
          })
        }
      }
      axios({
        method: 'post',
        url: 'api/xcoa-mobile/v1/spicengineconstrucebase/exportDataList',
        responseType: 'blob',
        data: this.expressions,
        headers: {
          'Content-Type': 'application/json',
        },
      }).then((res) => {
        const url = URL.createObjectURL(res.data)
        download(url, '集团公司在审重点工程建设项目信息表.xlsx')
      })
    },
    radioOnChange(e) {
      if (this.selectedType !== e.target.value) {
        this.expressions = []
        this.selectedType = e.target.value
        if (e.target.value === 1) {
          this.expressions.push({
            dataType: 'str',
            name: 'stateFlag',
            op: 'eq',
            stringValue: 'true',
          })
        } else if (e.target.value === 2) {
          this.expressions.push({
            dataType: 'str',
            name: 'stateFlag',
            op: 'eq',
            stringValue: 'false',
          })
        }
      }
      this.$refs.sqapplyDataTable.clearSelection()
    },
    // 查询
    handleSearch() {
      this.expressions = []
      if (this.radioValue === 1) {
        this.expressions.push({
          dataType: 'str',
          name: 'stateFlag',
          op: 'eq',
          stringValue: 'true',
        })
      } else if (this.radioValue === 2) {
        this.expressions.push({
          dataType: 'str',
          name: 'stateFlag',
          op: 'eq',
          stringValue: 'false',
        })
      }
      // 报送单位
      if (this.formData.submitUnitName) {
        this.expressions.push({
          dataType: 'str',
          name: 'submitUnitName',
          op: 'like',
          stringValue: `${this.formData.submitUnitName}`,
        })
      }
      // 报送月份
      if (this.formData.submitMonth) {
        this.expressions.push({
          dataType: 'str',
          name: 'submitMonth',
          op: 'eq',
          stringValue: `${this.formData.submitMonth}`,
        })
      }
      // 报送人
      if (this.formData.submitUserName) {
        this.expressions.push({
          dataType: 'str',
          name: 'submitUserName',
          op: 'like',
          stringValue: `${this.formData.submitUserName}`,
        })
      }
      // 报送时间
      if (this.strOrArr(this.formData.submitDate)) {
        if (this.formData.submitDate[0] === null || this.formData.submitDate[0] === '') {
          this.formData.submitDate = null
        } else {
          this.expressions.push({
            dataType: 'str',
            name: 'submitDate',
            op: 'ge',
            stringValue: `${this.formData.submitDate[0].format('YYYY-MM-DD')}`,
          })
          this.expressions.push({
            dataType: 'str',
            name: 'submitDate',
            op: 'le',
            stringValue: `${this.formData.submitDate[1].format('YYYY-MM-DD')}`,
          })
        }
      }
    },

    // 删除数据
    deleteRows(record) {
      const userInfo = getUserInfo()
      const selecteFlowState = this.$refs.projectFDataTable.getSelectedRows()
      const selectedRowKeys = this.$refs.projectFDataTable.getSelectedRowKeys()
      if (selectedRowKeys.length === 0) {
        Modal.info({
          content: '请选择需要删除的数据！',
        })
        return
      }

      axios({
        url: 'api/xcoa-mobile/v1/spicengineconstrucebase/findHasPermission',
        method: 'post',
      }).then((res) => {
        if (res.data === true) {
          this.flagdelete()
        } else {
          let delFlag = true
          selecteFlowState.forEach((item) => {
            if (item.creatorName !== userInfo.name) {
              delFlag = false
            }
          })
          if (delFlag) {
            this.flagdelete()
          } else {
            Modal.warning({
              title: '提示',
              content: '删除失败，不可删除他人创建的流程！',
            })
          }
        }
      })
    },

    flagdelete() {
      let flag = true
      const rows = this.$refs.projectFDataTable.getSelectedRows()
      rows.forEach((r) => {
        if (r.endType) {
          if (r.endType !== 0) {
            flag = false
          }
        }
      })
      if (!flag) {
        Modal.error({
          title: '删除失败：存在不是起草状态的数据',
        })
        this.loading = false
      } else {
        const selectedRowKeys = this.$refs.projectFDataTable.getSelectedRowKeys()
        Modal.confirm({
          title: '你确定删除这项内容吗？',
          content: '删除这条数据后，就无法恢复初始的状态。',
          okText: '删除',
          okType: 'danger',
          onOk: () => {
            this.loading = true
            const params = {
              ids: selectedRowKeys.join(','),
            }

            PageService.delete(params, this.formId).then((res) => {
              message.success('删除成功')
              if (res.status === 200) {
                this.$refs.projectFDataTable.clearSelection()
                this.refresh()
                this.loading = false
              }
            })
          },
        })
      }
    },
    refresh() {
      return this.$refs.projectFDataTable.refresh(true)
    },
    rowClick(record) {
      if (record.flowState === '起草' && record.creatorAccount === getUserInfo().account) {
        const url = '/sd-webflow/pages/draft/' + record.instId // 编辑面要打开的路由地址
        crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
          if (refreshFlag) {
            // 这里写或者调刷新的方法
            this.refreshDataTable()
          }
        })
      } else {
        const url = '/sd-webflow/done-pages/' + record.instId
        crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
          if (refreshFlag) {
            // 这里写或者调刷新的方法
            this.refreshDataTable()
          }
        })
      }
    },
    refreshDataTable() {
      this.$refs.projectFDataTable.clearSelection()
      this.$refs.projectFDataTable.refresh()
    },
  },
}
</script>

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

:global(.auditsqapplylist) {
  :global(span > .ant-btn:last-child) {
    color: #fff;
    background-color: #1890ff;
    border-color: #1890ff;
  }

  :global(.ant-radio-group) {
    // position: relative;
    // top: 40px;
    float: left;
    line-height: 40px;
  }
}
</style>
