<template>
  <div>
    <a-card class="reporttablecardxm">
      <!-- 高级搜索组件 -->
      <audit-advanced-query
        :expand="expand"
        :class="$style.advancedQuery"
        :search-data="formData"
        :ref-name="searchform"
        :search-style="{ height: '220px', left: '10px', top: '60px' }"
        :search-fun="handleSearch"
        @searchedClick="searchedClick"
      >
        <template>
          <a-row>
            <a-col :span="12">
              <a-form-model-item :label="'项目名称'" prop="projectName">
                <a-input v-model="formData.projectName" allow-clear />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item :label="'单位名称'" prop="secUnitName">
                <a-input v-model="formData.secUnitName" allow-clear />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-model-item :label="'投资方式'" prop="investmentMethod">
                <a-input v-model="formData.investmentMethod" allow-clear />
                <!-- <a-select v-model="formData.investmentMethod" :allow-clear="true">
                  <a-select-option :value="0"> 基建 </a-select-option>
                  <a-select-option :value="1"> 并购 </a-select-option>
                  <a-select-option :value="2"> 合作开发 </a-select-option>
                </a-select> -->
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item :label="'产业类别'" prop="industryCategory">
                <a-input v-model="formData.industryCategory" allow-clear />
                <!-- <a-select v-model="formData.industryCategory" :allow-clear="true">
                  <a-select-option :value="0"> 风电 </a-select-option>
                  <a-select-option :value="1"> 光伏 </a-select-option>
                  <a-select-option :value="2"> 储能 </a-select-option>
                  <a-select-option :value="3"> 其他 </a-select-option>
                </a-select> -->
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="23">
              <a-form-model-item :label="'完成竣工财务决算或并购时间'" prop="mergerTime">
                <a-range-picker v-model="formData.mergerTime" />
                <!-- <a-date-picker
                  v-model="formData.mergerTime"
                  required="true"
                  format="YYYY-MM-DD"
                  :allow-clear="true"
                  @change="onChange"
                ></a-date-picker> -->
              </a-form-model-item>
            </a-col>
          </a-row>
        </template>
      </audit-advanced-query>
      <a-radio-group
        v-model="radioValue"
        allow-clear
        :class="$style.radioGroup"
        @change="radioOnChange"
      >
        <a-radio :value="1"> 全部 </a-radio>
        <a-radio :value="2"> 待处理 </a-radio>
      </a-radio-group>
      <sd-data-table-ex
        ref="SJZXDataTable"
        :filter-expressions="expressions"
        :columns="columns"
        :actions="actions"
        form-id="spicProjectPostEvaluation"
        :data-url="dataurl"
        :search-fields="[
          'projectName',
          'investmentMethod',
          'secUnitName',
          'industryCategory',
          'mergerTime',
        ]"
        show-selection
        :show-advance-query="true"
        @searchbtnClick="searchbtnClick"
      >
        <div slot="islink" slot-scope="text, record">
          <a @click="rowClick(record)">{{ text }}</a>
        </div>
      </sd-data-table-ex>
    </a-card>
  </div>
</template>

<script>
import { getUserInfo } from '@/common/store-mixin'
import download from '@/common/services/download'
import { message, Modal } from 'ant-design-vue'
import PageService from '@/common/services/page-service'
import axios from '@/common/services/axios-instance'
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 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/xm-project-post-evaluation-list-import'

export default {
  name: 'XmProjectPostEvaluationList',
  metaInfo: {
    title: '后评价项目信息',
  },
  components: {
    ...components,
    auditAdvancedQuery,
  },
  mixins: [auditAdvancedQueryMixins, auditAdvancedGroupMixins],
  data() {
    return {
      radioValue: 1,
      searchform: 'searchform',
      dataurl: 'api/xcoa-mobile/v1/spicprojectpostevaluation/all-list',
      expressions: [],
      formData: {
        projectName: '',
        investmentMethod: null,
        industryCategory: null,
        mergerTime: '',
        secUnitName: '',
      },
      exportIds: [],
      formId: 'spicProjectPostEvaluation',
      columns: [
        {
          title: '序号',
          dataIndex: 'sortNumber',
          width: '80px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        {
          title: '项目名称',
          dataIndex: 'projectName',
          width: '220px',
          scopedSlots: { customRender: 'islink' },
        },
        {
          title: '单位名称',
          dataIndex: 'secUnitName',
          width: '220px',
        },
        {
          title: '并购项目完成并购、基建项目和合作开发项目完成竣工财务决算满1年及以上',
          dataIndex: 'mergerProject',
          width: '180px',
        },
        {
          title: '投资额1000万元以上',
          dataIndex: 'investmentAmount',
          width: '160px',
        },
        {
          title: '投资方式',
          dataIndex: 'investmentMethod',
          width: '100px',
        },
        {
          title: '产业类别',
          dataIndex: 'industryCategory',
          width: '100px',
        },
        {
          title: '完成竣工财务决算或并购时间',
          dataIndex: 'mergerTime',
          sdRender: TableColumnTypes.date,
          sorter: true,
          // defaultSortOrder: 'asc',
          width: '180px',
        },
        {
          title: '编辑人员',
          dataIndex: 'creatorName',
          sdHidden: true,
        },
        {
          title: '编辑日期',
          dataIndex: 'creationTime',
          sortDirections: 'descend',
          defaultSortOrder: 'descend',
          sdRender: TableColumnTypes.date,
          sdHidden: true,
        },
        {
          title: '报送状态',
          dataIndex: 'pubStatus',
          width: '120px',
        },
        {
          title: '是否新数据',
          dataIndex: 'isNewData',
          sdHidden: true,
        },
      ],
      actions: [
        {
          label: '删除',
          id: 'delete',
          permission: null,
          type: TableActionTypes.batch,
          callback: this.deleteRows,
        },
        // {
        //   label: '新建',
        //   id: 'new',
        //   type: TableActionTypes.primary, // 新建按钮，不需要回调，自动处理
        //   permission: 'create', // 纯前端操作，不需要权限控制
        //   callback: () => {
        //     const url = '/sd-flow-guide?code=SPIC_AUDIT_HPJXMXX' // 新页面要打开的路由地址
        //     crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        //       if (refreshFlag) {
        //         // 这里写或者调刷新的方法
        //         this.refresh()
        //       }
        //     })
        //   },
        // },
        {
          label: '生成数据',
          id: 'newData',
          permission: null,
          callback: this.newData, // 纯前端操作，不需要权限控制
        },

        {
          label: '导出',
          id: 'export',
          permission: null,
          callback: () => {
            let idArr = this.$refs.SJZXDataTable.getSelectedRowKeys()
            if (idArr === undefined || idArr.length === 0) {
              idArr = this.exportIds
            }
            this.handleExport(idArr)
          },
        },
      ],
    }
  },
  created() {},
  mounted() {},
  methods: {
    // 生成数据
    newData() {
      axios({
        url: `api/xcoa-mobile/v1/spicprojectpostevaluation/generateDatas?`,
        method: 'post',
      }).then((res) => {
        if (res.status === 200) {
          // Modal.warning({
          //   title: '提示',
          //   content: '生成数据成功',
          // })
          this.refresh()
        }
      })
    },
    handleExport(ids) {
      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.projectName) {
        this.expressions.push({
          dataType: 'str',
          name: 'projectName',
          op: 'like',
          stringValue: `${this.formData.projectName}`,
        })
      }
      // 投资方式
      if (this.formData.investmentMethod) {
        this.expressions.push({
          dataType: 'str',
          name: 'investmentMethod',
          op: 'like',
          stringValue: `${this.formData.investmentMethod}`,
        })
      }
      // 产业类别
      if (this.formData.industryCategory) {
        this.expressions.push({
          dataType: 'str',
          name: 'industryCategory',
          op: 'like',
          stringValue: `${this.formData.industryCategory}`,
        })
      }
      // 完成竣工财务决算或并购时间
      if (this.strOrArr(this.formData.mergerTime)) {
        if (this.formData.mergerTime[0] === null) {
          this.formData.mergerTime = null
        } else {
          this.expressions.push({
            dataType: 'str',
            name: 'mergerTime',
            op: 'ge',
            stringValue: `${this.formData.mergerTime[0].format('YYYY-MM-DD')}`,
          })
          this.expressions.push({
            dataType: 'str',
            name: 'mergerTime',
            op: 'le',
            stringValue: `${this.formData.mergerTime[1].format('YYYY-MM-DD')}`,
          })
        }
      }
      // 单位名称
      if (this.formData.secUnitName) {
        this.expressions.push({
          dataType: 'str',
          name: 'secUnitName',
          op: 'like',
          stringValue: `${this.formData.secUnitName}`,
        })
      }
      axios({
        url: 'api/xcoa-mobile/v1/spicprojectpostevaluation/exportDatas',
        method: 'post',
        data: this.expressions,
        responseType: 'blob',
      }).then((res) => {
        if (res.status === 200) {
          const url = URL.createObjectURL(res.data)
          const filename = res.headers['content-disposition']
          const fname = filename.substring(filename.indexOf('filename=') + 9, filename.length)
          download(url, decodeURI(fname))
        }
      })
    },
    // handleExport(ids) {
    //   if (!ids || ids.length === 0) {
    //     Modal.info({
    //       content: '请选择需要导出的数据！',
    //     })
    //   } else {
    //     axios({
    //       url: 'api/xcoa-mobile/v1/spicprojectpostevaluation/exportDatas',
    //       method: 'post',
    //       data: ids,
    //       responseType: 'blob',
    //     }).then((res) => {
    //       if (res.status === 200) {
    //         const url = URL.createObjectURL(res.data)
    //         const filename = res.headers['content-disposition']
    //         const fname = filename.substring(filename.indexOf('filename=') + 9, filename.length)
    //         download(url, decodeURI(fname))
    //       }
    //     })
    //   }
    // },

    onChange(value) {
      if (value) {
        this.formData.mergerTime = value.format('YYYY-MM-DD')
      } else {
        this.formData.mergerTime = ''
      }
    },
    // 删除数据
    deleteRows(record) {
      const userInfo = getUserInfo()
      const selecteFlowState = this.$refs.SJZXDataTable.getSelectedRows()
      const selectedRowKeys = this.$refs.SJZXDataTable.getSelectedRowKeys()
      if (selectedRowKeys.length === 0) {
        Modal.info({
          content: '请选择需要删除的数据！',
        })
        return
      }

      axios({
        url: 'api/xcoa-mobile/v1/spicprojectpostevaluation/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.SJZXDataTable.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.SJZXDataTable.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.SJZXDataTable.clearSelection()
                this.refresh()
                this.loading = false
              }
            })
          },
        })
      }
    },
    refresh() {
      return this.$refs.SJZXDataTable.refresh(true)
    },
    rowClick(record) {
      debugger
      const userInfo = getUserInfo()
      if (record.creatorName === userInfo.name && record.endType !== 5) {
        window.open('#/sd-webflow/pages/draft/' + record.instId)
      } else if (record.creatorName === userInfo.name && record.endType === 5) {
        window.open('#/sd-webflow/done-pages/' + record.instId)
      } else {
        window.open('#/sd-webflow/done-pages/' + record.instId)
      }
      // axios({
      //   url: 'api/xcoa-mobile/v1/spicprojectpostevaluation/findHasPermission',
      //   method: 'post',
      // }).then((res) => {
      //   debugger
      //   if (res.data === true) {
      //     if (
      //       record.creatorName === userInfo.name &&
      //       (record.flowState === '起草') | (record.flowState === '开始')
      //     ) {
      //       window.open('#/sd-webflow/pages/draft/' + record.instId)
      //     } else {
      //       window.open('#/sd-webflow/done-pages/' + record.instId)
      //     }
      //   } else if ((record.flowState === '起草') | (record.flowState === '开始')) {
      //     window.open('#/sd-webflow/pages/draft/' + record.instId)
      //   } else {
      //     window.open('#/sd-webflow/done-pages/' + record.instId)
      //   }
      // })
    },

    radioOnChange(e) {
      if (this.selectedType !== e.target.value) {
        this.selectedType = e.target.value
        if (e.target.value === 1) {
          this.dataurl = 'api/xcoa-mobile/v1/spicprojectpostevaluation/all-list'
          this.radioValue = 1
        } else if (e.target.value === 2) {
          this.dataurl = 'api/xcoa-mobile/v1/spicprojectpostevaluation/todo-list'
          this.radioValue = 2
        }
      }
    },
    // 判断数组或字符串为null或长度为0
    strOrArr(strOrArr) {
      return strOrArr !== null && strOrArr.length > 0
    },
    // 查询
    handleSearch() {
      this.expressions = []
      // 项目名称
      if (this.formData.projectName) {
        this.expressions.push({
          dataType: 'str',
          name: 'projectName',
          op: 'like',
          stringValue: `${this.formData.projectName}`,
        })
      }
      // 投资方式
      if (this.formData.investmentMethod) {
        this.expressions.push({
          dataType: 'str',
          name: 'investmentMethod',
          op: 'like',
          stringValue: `${this.formData.investmentMethod}`,
        })
      }
      // 产业类别
      if (this.formData.industryCategory) {
        this.expressions.push({
          dataType: 'str',
          name: 'industryCategory',
          op: 'like',
          stringValue: `${this.formData.industryCategory}`,
        })
      }
      // 完成竣工财务决算或并购时间
      if (this.strOrArr(this.formData.mergerTime)) {
        if (this.formData.mergerTime[0] === null) {
          this.formData.mergerTime = null
        } else {
          this.expressions.push({
            dataType: 'str',
            name: 'mergerTime',
            op: 'ge',
            stringValue: `${this.formData.mergerTime[0].format('YYYY-MM-DD')}`,
            // stringValue: new Date(
            //   this.formData.mergerTime[0].format('YYYY-MM-DD') + ' 00:00:00'
            // ).valueOf(),
          })
          this.expressions.push({
            dataType: 'str',
            name: 'mergerTime',
            op: 'le',
            stringValue: `${this.formData.mergerTime[1].format('YYYY-MM-DD')}`,
            // stringValue: new Date(
            //   this.formData.mergerTime[1].format('YYYY-MM-DD') + ' 23:59:59'
            // ).valueOf(),
          })
        }
      }
      // if (this.formData.mergerTime) {
      //   const timeValue = Date.parse(new Date(this.formData.mergerTime).toString())
      //   this.expressions.push({
      //     dataType: 'str',
      //     name: 'mergerTime',
      //     op: 'eq',
      //     stringValue: `${this.formData.mergerTime}`,
      //     // longValue: timeValue,
      //   })
      // }
      // 单位名称
      if (this.formData.secUnitName) {
        this.expressions.push({
          dataType: 'str',
          name: 'secUnitName',
          op: 'like',
          stringValue: `${this.formData.secUnitName}`,
        })
      }
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.radioGroup {
  position: absolute;
  top: 30px;
  left: 20px;
}
.advancedQuery {
  :global(.ant-col .ant-form-item-label) {
    width: 20% !important;
  }
  :global(.reporttablecardxm) {
    :global(.ant-table-body) {
      height: auto !important;
      min-height: auto !important;
      overflow: auto;
    }
  }
  :global(.ant-col .ant-form-item-control-wrapper) {
    width: 80% !important;
  }
}
</style>
