<template>
  <a-card :class="$style.rectPlanProjectlist">
    <div :class="[$style.btns]">
      <audit-advanced-export
        ref="rectplanprojectExport"
        :class-style="[$style.buttonSpacing]"
        :v-if="false"
        :config-id="191"
        :exclebxh="false"
      ></audit-advanced-export>
    </div>
    <!-- 高级搜索区域 -->
    <audit-advanced-query
      :expand="expand"
      :class="$style.advancedQuery"
      :search-data="advSearchForm"
      :ref-name="searchform"
      :search-style="{ height: '220px', left: '20px', top: '50px' }"
      :search-fun="advSearch"
      @searchedClick="searchedClick"
      @resetForm="resetForm"
    >
      <template>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="审计机构">
              <a-form-model-item>
                <AuditGroupPicker
                  v-model="auditUnit"
                  :single="true"
                  :read-only="false"
                  :root-node="rootNode"
                />
              </a-form-model-item>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="项目名称" prop="projectName">
              <a-input v-model="advSearchForm.projectName" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="项目编号" prop="projectCode">
              <a-input v-model="advSearchForm.projectCode" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="整改责任主体" prop="auditedUnit">
              <!-- <a-input v-model="advSearchForm.auditedUnit" /> -->
              <sd-group-picker
                ref="unitSelect"
                v-model="advSearchForm.auditedUnit"
                :single="true"
                :read-only="false"
                @change="changeunit"
              />
            </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-row>
      </template>
    </audit-advanced-query>
    <div :class="$style.rectPlanProjectlist">
      <sd-data-table-ex
        ref="dataTable"
        :projectlist="true"
        :columns="columns"
        :actions="actions"
        show-selection
        form-id="iamWorkRectProject"
        data-url="api/xcoa-mobile/v1/rectPlan-project/all-list"
        :filter-expressions="tableExpressions"
        :show-advance-query="true"
        :search-fields="['projectName']"
        :custom-delete-fun="deleteRows"
        @searchbtnClick="searchbtnClick"
      >
        <div slot="isLink" slot-scope="text, record">
          <a :title="text" @click="linkProject(record)">{{ text }}</a>
        </div>
        <div slot="opt" slot-scope="text, record" :class="$style.operatecol">
          <!-- 管理员 项目组长 项目副组长 则可以变更 -->
          <span v-for="(bt, index) in buttonsfortable" :key="index">
            <a-button
              v-if="record.changeButtons === 'true'"
              type="link"
              size="small"
              @click="optbuttonClick(bt.id, record)"
              >{{ bt.label }}
              <!-- <sd-icon :type="bt.icontype" :theme="bt.theme"/> -->
            </a-button>
          </span>
        </div>
      </sd-data-table-ex>
    </div>
    <div v-show="false">
      <sd-user-picker
        ref="assignTeamLeader"
        v-model="mainSendUnit"
        :single="true"
        :read-only="false"
        @change="change"
      />
      <sd-user-picker
        ref="assignTeamAuditedContacts"
        v-model="mainSendUnit"
        :single="true"
        :read-only="false"
        @change="changeAuditedContacts"
      />
    </div>
  </a-card>
</template>

<script>
import { message, Modal } from 'ant-design-vue'
import { getUserInfo } from '@/common/store-mixin'
import axios from '@/common/services/axios-instance'
import errorUtil from '@/common/services/error-util'
import TableActionTypes from '@/common/services/table-action-types'
import TableColumnTypes from '@/common/services/table-column-types'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import auditAdvancedQuery from '../../components/audit-advanced-query.vue'
import auditAdvancedQueryMixins from '../../components/audit-advanced-query-mixins'
import auditAdvancedExport from '../../components/audit-advanced-export'
import AuditRectplanprojectService from './audit-rectplanproject-service'
import AuditGroupPicker from '../../components/picker/audit-group-picker.vue'
import components from './_import-components/audit-rectplanproject-list-import'

export default {
  name: 'AuditRectplanprojectList',
  metaInfo: {
    title: '整改计划列表',
  },
  components: { ...components, auditAdvancedQuery, auditAdvancedExport, AuditGroupPicker },
  mixins: [auditAdvancedQueryMixins],
  data() {
    return {
      endOpen: false,
      year: null,
      searchYear: '',
      auditUnit: [],
      rootNode: {},
      auditUnitName: '',
      yearArry: [],
      searchValue: '',
      mainSendUnit: [],
      checkboxValue: false,
      pageId: 'audit/project/iamAuditProject',
      columns: [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: '项目名称',
          dataIndex: 'projectName',
          width: '450px',
          scopedSlots: { customRender: 'isLink' },
        },
        {
          title: '项目编号',
          defaultSortOrder: 'descend',
          dataIndex: 'projectCode',
          width: '180px',
        },
        {
          title: '项目Id',
          dataIndex: 'projectId',
          sdHidden: true,
        },
        {
          title: '跟踪人账号',
          dataIndex: 'resppersonsAccount',
          sdHidden: true,
        },
        {
          title: '项目来源',
          dataIndex: 'projectSource',
          sdHidden: true,
        },
        {
          title: '整改责任主体',
          dataIndex: 'auditedUnitName',
          width: '200px',
        },
        {
          title: '整改责任主体联系人',
          // sorter: true,
          dataIndex: 'auditedContactsName',
          width: '180px',
        },
        {
          title: '整改责任主体联系人账号',
          dataIndex: 'auditedContactsAccount',
          sdHidden: true,
        },
        {
          title: '整改跟踪人',
          sorter: true,
          dataIndex: 'resppersonsName',
          width: '140px',
        },
        {
          title: '整改计划反馈截止日期',
          sorter: true,
          dataIndex: 'expectFinishDate',
          sdRender: TableColumnTypes.date,
          width: '200px',
          sdHidden: true,
        },
        {
          title: '当前状态',
          dataIndex: 'flowState',
          width: '150px',
          sdHidden: true,
        },
        { title: '文档状态', dataIndex: 'endType', width: '120px', sdHidden: true },
        {
          title: '当前处理人',
          dataIndex: 'currentUser',
          width: '150px',
          sdHidden: true,
        },
        {
          title: '操作',
          dataIndex: 'id',
          scopedSlots: { customRender: 'opt' },
          width: '260px',
        },
      ],
      actions: [
        {
          label: '新建',
          id: 'new',
          type: TableActionTypes.primary, // 新建按钮，不需要回调，自动处理
          permission: null, // 纯前端操作，不需要权限控制
          callback: this.createrectplanproject,
        },
        // {
        //   label: '复制整改计划',
        //   id: 'copyrectproject',
        //   permission: null, // 纯前端操作，不需要权限控制
        //   callback: this.copyrectproject,
        // },
        {
          label: '删除',
          id: 'delete',
          type: 'delete', // 删除按钮，不需要回调，会自动处理（对sd-data-table无效）
          permission: null,
        },
        // {
        //   label: '导出',
        //   id: 'export',
        //   permission: null,
        //   callback: this.export,
        // },
      ],
      tableExpressions: [],
      buttonsfortable: [
        {
          label: '指定跟踪人',
          id: 'changeleader',
          showCondition: '',
        },
        {
          label: '指定联系人',
          id: 'auditedContacts',
          showCondition: '',
        },
      ],
      searchform: 'searchform',
      expand: false,
      advSearchForm: {
        auditUnit: '',
        projectName: '',
        projectCode: '',
        auditedUnit: '',
        planYear: '',
      },
      itemStatusOptions: [],
      auditTypeOptions: [],
      auditModeOptions: [],
      projectId: '',
      setType: '',
      unitName: '',
    }
  },
  created() {
    let userInfo = getUserInfo()
    const params = {
      orgId: userInfo.deptId,
    }
    axios({
      url: 'api/xcoa-mobile/v1/iamorg/getCurrentUserGroup',
      method: 'get',
    }).then((res) => {
      userInfo = res.data
      params.orgId = res.data.id
      axios({
        url: 'api/xcoa-mobile/v1/iamorg/findIamOrg',
        method: 'post',
        params,
      }).then((res) => {
        const deptCode = userInfo.id.toString()
        const deptName = res.data.orgName
        this.rootNode = { code: deptCode, name: deptName, id: res.data.id }
        this.auditUnit = [this.rootNode]
        this.initedSteps++
        // 审计机构
        if (this.auditUnit[0] !== undefined) {
          this.tableExpressions.push({
            dataType: 'str',
            name: 'unitName',
            op: 'like',
            stringValue: this.auditUnit[0].name,
          })
        }
      })
    })
  },
  mounted() {},
  methods: {
    export() {
      this.$refs.rectplanprojectExport.exportdata()
    },
    changeunit(values) {
      this.unitName = ''
      values.forEach((element) => {
        this.unitName = element.name
      })
    },
    createrectplanproject() {
      const url = `/sd-flow-guide?code=PRODUCT_IAM_ZGJH` // 新页面要打开的路由地址
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          // 这里写或者调刷新的方法
          // this.refreshDataTable()
          this.$refs.dataTable.refresh()
        }
      })
    },
    onSearch(value) {
      this.tableExpressions = []
      if (value) {
        const expressions = []
        // 项目名称
        expressions.push({
          dataType: 'str',
          name: 'projectName',
          op: 'like',
          stringValue: `%${value}%`,
        })
        // 项目编号
        expressions.push({
          dataType: 'str',
          name: 'projectCode',
          op: 'like',
          stringValue: `%${value}%`,
        })
        this.tableExpressions.push({
          dataType: 'exps',
          op: 'or',
          expressionsValue: expressions,
        })
      }
    },
    advSearch() {
      this.tableExpressions = []
      // 审计机构
      if (this.auditUnit[0] !== undefined) {
        this.tableExpressions.push({
          dataType: 'str',
          name: 'unitName',
          op: 'like',
          stringValue: this.auditUnit[0].name,
        })
      }
      // 项目名称
      if (this.advSearchForm.projectName) {
        this.tableExpressions.push({
          dataType: 'str',
          name: 'projectName',
          op: 'like',
          stringValue: `%${this.advSearchForm.projectName}%`,
        })
      }
      // console.log(this.tableExpressions)
      // 项目编号
      if (this.advSearchForm.projectCode) {
        this.tableExpressions.push({
          dataType: 'str',
          name: 'projectCode',
          op: 'like',
          stringValue: `%${this.advSearchForm.projectCode}%`,
        })
      }
      // 整改责任主体
      if (this.advSearchForm.auditedUnit) {
        this.tableExpressions.push({
          dataType: 'str',
          name: 'auditedUnitName',
          op: 'like',
          stringValue: `%${this.unitName}%`,
        })
      }
      // 年度计划
      if (this.advSearchForm.planYear) {
        this.tableExpressions.push({
          dataType: 'str',
          name: 'planYear',
          op: 'eq',
          stringValue: `${this.advSearchForm.planYear}`,
        })
      }

      // this.expand = false
    },
    searchedClick() {
      this.expand = !this.expand
    },
    linkProject(record) {
      const userInfo = getUserInfo()
      debugger
      if (
        (record.flowState === '起草') | (record.flowState === '开始') &&
        record.currentUser === userInfo.name
      ) {
        const url = '/sd-webflow/pages/draft/' + record.instId // 编辑面要打开的路由地址
        crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
          if (refreshFlag) {
            // 这里写或者调刷新的方法
            this.$refs.dataTable.refresh()
          }
        })
      } else {
        window.open('#/sd-webflow/done-pages/' + record.instId)
      }
    },
    // 项目组长配置保存
    change(val) {
      const obj = []
      if (val.length > 0) {
        return new Promise((resolve) => {
          AuditRectplanprojectService.changeTeamEditor(
            this.projectId,
            'iamWorkRectProject',
            val
          ).then((res) => {
            if (res.data) {
              this.$refs.dataTable.clearSelection()
              this.$refs.dataTable.refresh()
            }
          })
        })
      } else {
        Modal.warning({
          title: '提示',
          content: '请选择人员!',
        })
      }
    },
    // 项目组长配置保存(整改责任主体联系人)
    changeAuditedContacts(val) {
      const obj = []
      if (val.length > 0) {
        return new Promise((resolve) => {
          AuditRectplanprojectService.changeTeamAuditContactsEditor(
            this.projectId,
            'iamWorkRectProject',
            val
          ).then((res) => {
            if (res.data) {
              this.$refs.dataTable.clearSelection()
              this.$refs.dataTable.refresh()
            }
          })
        })
      } else {
        Modal.warning({
          title: '提示',
          content: '请选择人员!',
        })
      }
    },
    AdvSearchClick() {
      this.expand = !this.expand
    },
    copyrectproject() {
      const selectedRowKeys = this.$refs.dataTable.getSelectedRowKeys()
      if (selectedRowKeys.length === 0) {
        Modal.info({
          content: '请选择需要复制的数据！',
        })
        return false
      } else if (selectedRowKeys.length > 1) {
        Modal.info({
          content: '只能选择一个数据进行复制！',
        })
        return false
      }
      const selectRows = this.$refs.dataTable.getSelectedRows()
      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: 'rectattach' },
        ],
        pagePath: '/audit/rectPlanProject/iamWorkRectProject',
        ignoreFieldValue: '',
      }
      AuditRectplanprojectService.copy(params).then((res) => {
        this.linkProject({
          flowState: '起草',
          currentUser: getUserInfo().name,
          instId: res.data.instId,
        })
      })
    },

    optbuttonClick(val, record) {
      // 变更编辑人
      if (val === 'changeleader') {
        const jsonArry = []
        if (record.resppersonsAccount !== '' && record.resppersonsAccount !== null) {
          if (record.resppersonsAccount.indexOf(',') > -1) {
            const codes = record.resppersonsAccount.split(',')
            const names = record.resppersonsName.split(',')
            for (let i = 0; i < codes.length; i++) {
              jsonArry.push({ type: 'User', code: codes[i], name: names[i], attrs: [] })
            }
          } else {
            jsonArry.push({
              type: 'User',
              code: record.resppersonsAccount,
              name: record.resppersonsName,
              attrs: [],
            })
          }
        }
        this.mainSendUnit = jsonArry
        this.projectId = record.id
        setTimeout(() => {
          this.$refs.assignTeamLeader.openPicker()
        }, 0)
      }
      // 变更整改责任主体联系人
      if (val === 'auditedContacts') {
        const jsonArry = []
        if (record.auditedContactsAccount !== '' && record.auditedContactsAccount !== null) {
          if (record.auditedContactsAccount.indexOf(',') > -1) {
            const codes = record.auditedContactsAccount.split(',')
            const names = record.auditedContactsName.split(',')
            for (let i = 0; i < codes.length; i++) {
              jsonArry.push({ type: 'User', code: codes[i], name: names[i], attrs: [] })
            }
          } else {
            jsonArry.push({
              type: 'User',
              code: record.auditedContactsAccount,
              name: record.auditedContactsName,
              attrs: [],
            })
          }
        }
        this.mainSendUnit = jsonArry
        this.projectId = record.id
        setTimeout(() => {
          this.$refs.assignTeamAuditedContacts.openPicker()
        }, 0)
      }
    },
    // 重置年份
    resetForm() {
      this.advSearchForm.auditedUnit = ''
      this.unitName = ''
    },
    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'
      }
    },
    handleEndOpenChange(open) {
      this.endOpen = open
    },
    deleteRows() {
      // debugger
      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)
                let query = {}
                query = {
                  rectId: selectedRowKeys.join(','),
                }
                axios({
                  url: `api/xcoa-mobile/v1/spicrectfeedback/deleteByrectId?rectId=${query.rectId}`,
                  method: 'get',
                }).then((res) => {
                  console.log('删除子表数据成功')
                })
              })
              .catch((err) => {
                const msg = errorUtil.getMessage(err) || '删除失败'
                message.error(msg)
              })
              .finally(resolve)
          },
          onCancel: () => {
            resolve()
          },
        })
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.btns {
  position: absolute;
  top: 24px;
  right: 20.5px;
  z-index: 100;
}
.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;
  }
}
.buttonSpacing {
  margin-left: 5px;
}
</style>
