<template>
  <div :class="[$style.wrapHeight, $style.warpper]">
    <xm-search-form
      v-if="onlListColumnDefs.length"
      v-show="showAdvSearch"
      ref="searchForm"
      :onl-list-column-defs="onlListColumnDefs"
      @search="(value) => (customFilterExpressions = value)"
      @close="() => (advSearchBtnActived = false)"
    />
    <a-card>
      <div :class="[$style.btns]">
        <audit-advanced-export
          v-if="true"
          ref="exportBtn"
          :class-style="[$style.buttonSpacing]"
          :exclebxh="false"
          :expressions="expressions"
          :config-id="51"
          :v-show="false"
        />
      </div>
      <sd-data-table
        :key="key"
        :row-key="'id'"
        ref="cpmProjectList"
        :editnode="editnode"
        form-id="onlhead:cd78040cdda84c6b90b2c688d9bfbaa1"
        :data-url="'api/xcoa-mobile/v1/cpm-project/list'"
        :columns="columns"
        show-selection
        :search-fields="searchFields"
        :class="{ [$style.fuzzyAdvSearch]: fuzzyAndAdvSearch }"
        :filter-expressions="expressions"
        :process-res="processRes"
        :process-req="processReq"
      >
        <template slot="islink" slot-scope="text, record">
          <a :title="text" @click="open(record)">{{ text }}</a>
        </template>
        <template slot="action" slot-scope="text, record">
          <a type="link" @click="rowClick(record)" v-if="record.open">打开作业</a>
          <span v-else>打开作业</span>
        </template>
        <!-- 既有高级查询，又有模糊查询，显示高级查询图标 -->
        <template v-if="fuzzyAndAdvSearch" slot="headerPrefix">
          <sd-advance-search-btn
            :actived="advSearchBtnActived"
            :class="$style.advsearchbtn"
            @click="switchSearch"
          />
        </template>
      </sd-data-table>
    </a-card>
  </div>
</template>

<script>
import axios from '@/common/services/axios-instance'
import systemManage from '@/system-manage/system-manage'
import TableColumnTypes from '@/common/services/table-column-types'
import sdAdvanceSearchBtn from '@/application-manage/sd-advance-search-btn.vue'
import auditAdvancedExport from '@product/iam/components/audit-advanced-export'
import xmSearchForm from '@product/iam/components/xm-search-form.vue'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import CpmService from '../cpm-service'
import components from './_import-components/cpm-project-list-import'
export default {
  name: 'CpmProjectList',
  metaInfo: {
    title: '合规项目列表',
  },
  components: {
    ...components,
    sdAdvanceSearchBtn,
    xmSearchForm,
    auditAdvancedExport,
  },
  mixins: [],
  data() {
    return {
      yearArry: [],
      waterMark: systemManage.getFormWaterMark(),
      flag: true,
      recordId: '',
      editnode: false, // 列表是否可以新建
      key: 0,
      treeData: [],
      searchform: 'searchform',
      formData: {
        title: '',
        checkType: null,
        startDept: null,
      },
      checkTypeOptions: [],
      columns: [
        {
          title: '序号',
          customRender: (text, record, index) => (record.isChildren ? '' : `${index + 1}`),
          width: '70px',
        },
        { dataIndex: 'id', sdHidden: true },
        {
          title: '项目名称',
          dataIndex: 'title',
          scopedSlots: { customRender: 'islink' },
        },
        {
          title: '项目编号',
          dataIndex: 'currentNumber',
          width: '200px',
        },

        {
          title: '检查类型',
          dataIndex: 'checkType',
          width: '100px',
        },
        {
          title: '发起机构',
          dataIndex: 'startDeptName',
          width: '150px',
        },
        {
          title: '被检查单位',
          dataIndex: 'checkedDeptNames',
        },
        {
          title: '项目组长',
          dataIndex: 'submitterNames',
          width: '150px',
        },
        {
          title: '操作',
          dataIndex: '',
          scopedSlots: { customRender: 'action' },
          align: 'center',
          width: '100px',
        },
        {
          dataIndex: 'creationTime',
          sdHidden: true,
          sorter: true,
          defaultSortOrder: 'ascend', // 没有点击任何排序列时，默认的排序列
        },
      ],
      expressions: [],
      catalogId: null,
      catalogName: '',
      auditMattersPath: '',
      visible: false,
      showfuzzySearch: true, // builder-高级搜索开始
      advSearchBtnActived: false,
      onlListColumnDefs: [
        {
          attrFD: {
            clickable: true,
          },
          fieldId: 'title',
          fieldName: '项目名称',
          fieldType: 'string',
          isShowForm: 1,
          search: 1,
          searchConfigurable: true,
          searchMode: null,
        },
        {
          attrFD: {
            clickable: true,
          },
          fieldAttr: {
            appDict: [
              {
                id: '259493279754747904',
                text: '合规检查立项',
              },
            ],
            appDictId: '259493279754747904',
            dict: [],
            multiple: 'false',
            selectListItem: [
              {
                label: '违规调查',
                value: 'wg',
              },
              {
                label: '合规检查',
                value: 'hg',
              },
            ],
          },
          fieldAttrFD: {
            category: 'basic',
            cid: 'sd-radio',
            columns: 2,
            formItemProps: {
              inputProps: {
                dep: { _pending: false, id: 37770, subs: [] },
                mock: false,
                shallow: false,
                value: {},
                vmCount: 0,
              },
            },
            id: '1676516153680-4',
            listItemType: 'appDict',
          },
          fieldId: 'checkType',
          fieldName: '检查类型',
          fieldType: 'selectlist',
          isShowForm: 1,
          search: 1,
          searchConfigurable: true,
          searchMode: null,
        },
        {
          attrFD: {
            clickable: false,
            includeSub: true,
          },
          fieldAttr: {
            isUpdate: 'true',
            lev: 'COMPANY',
            maxLength: '100',
            setValueOnLoad: 'true',
            signFieldType: 'name',
            type: 'group',
            selectionType: 'Group',
          },
          fieldAttrFD: {
            cid: 'sd-sign-box',
            columns: 1,
            formItemProps: {
              inputProps: {
                dep: { _pending: false, id: 25709, subs: [] },
                mock: false,
                shallow: false,
                value: {},
                vmCount: 0,
              },
            },
            id: '1679906700480-1',
          },
          fieldId: 'startDept',
          fieldName: '发起机构',
          fieldType: 'selectgroup',
          isShowForm: 1,
          search: 1,
          searchConfigurable: true,
          searchMode: null,
        },
      ],
      customFilterExpressions: [],
    }
  },
  computed: {
    fuzzyAndAdvSearch() {
      // 既有高级查询，又有模糊查询
      return this.onlListColumnDefs.some((item) => item.search) && this.searchFields?.length > 0
    },
    showAdvSearch() {
      if (this.fuzzyAndAdvSearch) {
        return this.advSearchBtnActived
      }
      return this.onlListColumnDefs.length
    },
    searchFields() {
      if (this.showfuzzySearch && this.columns[0]) {
        return [this.columns[0].dataIndex]
      }
      return []
    },
  },
  mounted() {
    this.initDictionaryInfo()
  },
  watch: {
    customFilterExpressions: function() {
      this.handleSearch()
    },
  },
  // builder-高级搜索结束
  methods: {
    // 切换查询（高级查询、模糊查询）
    switchSearch() {
      if (this.advSearchBtnActived) {
        // 显示了高级查询，则重置
        this.$refs.searchForm.reset()
      } else {
        // 未显示高级查询，则置空模糊查询
        this.showfuzzySearch = false
        this.$refs.cpmProjectList.onSearchChange('')
        this.$nextTick(() => {
          this.showfuzzySearch = true
        })
      }
      this.advSearchBtnActived = !this.advSearchBtnActived
    },
    // 设置请求内容
    processReq(req) {
      const orderBy = 'creationTime asc'
      req.data.orderBy = orderBy
      return req
    },
    // 数据返回后，整理response对象
    processRes(res) {
      if (res.data) {
        res.data.forEach((item) => {
          // 判断监测单位是否有下级节点
          item.projectId = item.id
          if (item.subProjectBeans.length > 0) {
            item.children = []
            // 循环监测单位
            item.subProjectBeans.forEach((mitem, mindex) => {
              item.children.push({
                id: mitem.id,
                projectId: item.id,
                checkedDeptNames: mitem.checkedDeptNames,
                submitterNames: mitem.leaderName,
                open: mitem.open,
                isChildren: true,
              })
            })
          }
        })
      }
      return res
    },
    export() {},

    initDictionaryInfo() {
      CpmService.getDictData().then((res) => {
        if (res) {
          const dict = []
          res.data.forEach((r) => {
            dict.push({
              id: r.code,
              name: r.name,
            })
          })
          this.checkTypeOptions = dict
        }
      })
    },
    handleSearch() {
      this.expressions = []
      this.expressions = [...this.customFilterExpressions]
    },

    // 重置
    resetForm() {
      this.formData.title = ''
      this.formData.checkType = null
      this.formData.startDept = null
    },
    rowClick(record) {
      let url =
        `/cpm-project/cpm-check-plan?moduleId=267018022657347584&formListId=267018023269715968&projectId=` +
        record.projectId +
        '&groupId=1'
      if (record.isChildren) {
        url =
          `/cpm-project/cpm-check-plan?moduleId=267018022657347584&formListId=267018023269715968&projectId=` +
          record.projectId +
          '&groupId=' +
          record.id // 新页面要打开作业页面的路由地址
      }

      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          this.refresh()
        }
      })
    },
    open(record) {
      // const url = `/sd-webform?id=` + record.id + `&pageId=onl%3Acd78040cdda84c6b90b2c688d9bfbaa1` // 新页面要打开作业页面的路由地址
      const url = `/sd-webflow/done-pages/` + record.instId
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          this.refresh()
        }
      })
      // window.open('#/sd-webform?id=' + record.id + '&pageId=onl%3Acd78040cdda84c6b90b2c688d9bfbaa1')
    },
    refresh() {
      return this.$refs.cpmProjectList.refresh(true)
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
@import '@/application-manage/advance-search.scss';
.wrap-height {
  height: 100%;
  .row-height {
    display: flex;
    flex: auto;
    height: 100%;
    .rightcard {
      flex: 1;
      width: calc(100% - 20%);
      height: 100%;
    }
  }
}
.warpper {
  display: flex;
  flex-direction: column;
  height: 100%;
  > div:first-child {
    margin-bottom: 10px;
  }
  > div:last-child {
    flex: 1;
    min-height: auto;
  }
  :global(.ant-table-title) {
    display: none;
  }
  form + div {
    float: right;
  }
}
</style>
