<template>
  <div class="page">
    <el-form :inline="true" v-if="searchVisible" class="query-form m-b-10" ref="searchForm" :model="searchForm"
      @keyup.enter.native="refreshList()" @submit.native.prevent>
      <!-- 搜索框-->
      <el-form-item label="项目名称" prop="projectName">
        <el-input v-model="searchForm.projectName" placeholder="请输入项目名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="项目编号" prop="projectNumber">
        <el-input v-model="searchForm.projectNumber" placeholder="请输入项目编号" clearable></el-input>
      </el-form-item>
      <el-form-item v-if="showHideItem" label="项目经理1" prop="projectMasterName">
        <!--        <el-input v-model="searchForm.projectMasterName" placeholder="请输入项目经理" clearable></el-input>-->
        <!--        <UserSelect :limit='1' :modelValue="searchForm.projectMasterName" @update:modelValue='(value, label) => {searchForm.projectMasterName = value}'></UserSelect>-->
        <el-input v-model="searchForm.projectMasterName" placeholder="请选择项目经理1">
          <template #suffix>
            <el-button style="background-color: white;color: #1b1e25;border-color: white;" type="primary" slot="append"
              icon="el-icon-search" @click="openUserDia1">
            </el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item v-if="showHideItem" label="项目经理2" prop="realHeaderName">
        <!--        <el-input v-model="searchForm.projectMasterName" placeholder="请输入项目经理" clearable></el-input>-->
        <!--        <UserSelect :limit='1' :modelValue="searchForm.realHeaderName" @update:modelValue='(value, label) => {searchForm.realHeaderName = value}'></UserSelect>-->
        <el-input v-model="searchForm.realHeaderName" placeholder="请选择项目经理2">
          <template #suffix>
            <el-button style="background-color: white;color: #1b1e25;border-color: white;" type="primary" slot="append"
              icon="el-icon-search" @click="openUserDia2">
            </el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item v-if="showHideItem" label="创建人" prop="createBy.name">
        <!--        <el-input  v-model="searchForm.createBy.name" placeholder="请输入创建人" clearable></el-input>-->
        <!--			<UserSelect2 :limit='1' :modelValue="searchForm.createBy.name" @update:modelValue='(value, label) => {searchForm.createBy.name = value}'></UserSelect2>-->
        <el-input v-model="searchForm.createBy.name" placeholder="请选择创建人">
          <template #suffix>
            <el-button style="background-color: white;color: #1b1e25;border-color: white;" type="primary" slot="append"
              icon="el-icon-search" @click="openUserDia3">
            </el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item v-if="showHideItem" label="创建时间" prop="createDates">
        <el-date-picker placement="bottom-start" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
          v-model="searchForm.createDates" type="datetimerange" range-separator="至" start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <!--<el-form-item v-if="showHideItem" label="业务类型" prop="businessType">
			<SelectTree
				ref="typeTree"
				:props="{
                    value: 'id',             // ID字段名
                    label: 'name',         // 显示名称
                    children: 'children'    // 子级字段名
                  }"
				:url="'/finance-server/projectRecords/cw_project_business_type/list'"
				:value="searchForm.businessType"
				:clearable="true"
				:accordion="true"
				size="default"
				@getValue="(value) => {searchForm.businessType=value}"/>
		</el-form-item>-->
      <el-form-item v-if="showHideItem" label="报备类型" prop="reportType">
        <el-select v-model="searchForm.reportType" placeholder="请选择" style="width:100%;" clearable>
          <el-option v-for="item in $dictUtils.getDictList('cw_work_client_report_type')" :key="item.value"
            :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="showHideItem" label="报告日期" prop="reportDates">
        <el-date-picker clearable placement="bottom-start" format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss" v-model="searchForm.reportDates" type="datetimerange" range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item v-if="showHideItem" label="报告类型" prop="cwReportType">
        <el-select v-model="searchForm.cwReportType" clearable placeholder="请选择" style="width:100%;">
          <el-option v-for="item in $dictUtils.getDictList('cw_report_title_type')" :key="item.value"
            :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="showHideItem" label="项目分类" prop="projectClassification">
        <el-select v-model="searchForm.projectClassification" clearable placeholder="请选择" style="width:100%;">
          <el-option v-for="item in $dictUtils.getDictList('project_classification')" :key="item.value"
            :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="default" @click="showHide" :icon="showHideIcon">{{ showHideName }}</el-button>
        <el-button type="primary" @click="refreshList()" icon="el-icon-search">查询</el-button>
        <el-button @click="resetSearch()" icon="el-icon-refresh-right">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="jp-table top" style="">
      <vxe-toolbar :refresh="{ query: refreshList }" ref="toolbarRef" export custom>
        <template #buttons>
          <el-button v-if="hasPermission('cwProjectRecords:add')" type="primary" icon="el-icon-plus"
            @click="add()">新建</el-button>
          <!--          <el-button v-if="hasPermission('klg:question:del')" type="danger" icon="el-icon-delete" @click="del()" :disabled="$refs.questionsTable && $refs.questionsTable.getCheckboxRecords().length === 0" plain>删除</el-button>-->
          <el-button v-if="hasPermission('cwProjectRecords:import')" type="primary" @click="projectImport()" plain>导入</el-button>
        </template>
        <template #tools>
          <vxe-button text type="primary" :title="searchVisible ? '收起检索' : '展开检索'" icon="vxe-icon-search"
            class="tool-btn" @click="searchVisible = !searchVisible"></vxe-button>
        </template>
      </vxe-toolbar>
      <div style="height: calc(100% - 90px)">
        <vxe-table :key="tableKey" border="inner" auto-resize resizable height="auto" :loading="loading" size="small"
          ref="projectTable" show-header-overflow show-overflow highlight-hover-row :menu-config="{}"
          @sort-change="sortChangeHandle" :sort-config="{ remote: true }" :export-config="{
            remote: true,
            filename: `项目数据${moment(new Date()).format('YYYY-MM-DD')}`,
            sheetName: `项目数据${moment(new Date()).format('YYYY-MM-DD')}`,
            exportMethod: exportMethod,
            types: ['xls'],
            modes: ['current', 'selected', 'all']
          }" :data="dataList" :checkbox-config="{}">
          <vxe-column type="seq" width="60" title="序号"></vxe-column>
          <!--<vxe-column type="checkbox" width="40" ></vxe-column>-->
          <vxe-column min-width="230" align="center" title="项目名称" field="projectName">
            <template #default="scope">
              <el-link type="primary" :underline="false" v-if="hasPermission('cwProjectRecords:view')"
                @click="view(scope.row.id)">{{ scope.row.projectName }}</el-link>
              <el-link type="primary" :underline="false" v-else-if="hasPermission('cwProjectRecords:view')"
                @click="view(scope.row.id,)">{{ scope.row.projectName }}</el-link>
              <span v-else>{{ scope.row.projectName }}</span>
            </template>
          </vxe-column>
          <vxe-column min-width="140" align="center" title="项目编号" field="projectNumber"></vxe-column>
          <vxe-column min-width="110" align="center" title="项目规模(元)" field="projectMoney"></vxe-column>
          <!--<vxe-column min-width="160" align="center" title="业务类型" field="businessTypeName"></vxe-column>-->
          <vxe-column min-width="230" align="center" title="合同名称" field="contractName">
            <template #default="scope">
              <el-link type="primary" :underline="false"
                v-if="commonJS.isNotEmpty(scope.row.contractId) && commonJS.isNotEmpty(scope.row.contractName)"
                @click="viewContract(scope.row.contractId)">{{ scope.row.contractName }}</el-link>
              <span v-else style="color: red">暂无合同</span>
            </template>
          </vxe-column>
          <vxe-column min-width="80" align="center" title="创建人" field="createBy.name"></vxe-column>
          <vxe-column min-width="100" align="center" title="项目经理1" field="projectMasterName"></vxe-column>
          <vxe-column min-width="100" align="center" title="项目经理2" field="realHeaderName"></vxe-column>
          <vxe-column min-width="200" align="center" title="客户名称" field="clientContactsName"></vxe-column>
          <vxe-column min-width="120" align="center" title="创建时间" field="createTime"></vxe-column>
          <vxe-column title="操作" width="150px" fixed="right" align="center">
            <template #default="scope">
              <el-button
                v-if="hasPermission('cwProjectRecords:edit') && (scope.row.reportReview !== '1' || isAdmin) && (scope.row.createBy.id === $store.state.user.id || isAdmin || haveProjectIds.includes(scope.row.id))"
                text type="primary" size="small" @click="edit(scope.row.id)">修改</el-button>
              <!--              <el-button v-else-if="hasPermission('cwProjectRecords:edit')&&isAdmin" type="text"  size="small" @click="edit(scope.row.id)">修改</el-button>-->
              <!--              <el-button v-if="hasPermission('cwProjectRecords:edit')&&scope.row.createBy.id === $store.state.user.id&&scope.row.status==='2'" type="text"  size="small" @click="reback(scope.row)">撤回</el-button>-->
              <el-button
                v-if="hasPermission('cwProjectRecords:del') && (scope.row.reportReview !== '1' || isAdmin) && (scope.row.createBy.id === $store.state.user.id || isAdmin || haveProjectIds.includes(scope.row.id))"
                text type="primary" size="small" @click="del(scope.row.id)">删除</el-button>
              <!--              <el-button v-else-if="hasPermission('cwProjectRecords:del')&&isAdmin&&(scope.row.status==='1'||scope.row.status==='3' ||scope.row.status==='5')" type="text"   size="small" @click="del(scope.row.id)">删除</el-button>-->
            </template>
          </vxe-column>
        </vxe-table>
        <vxe-pager background size="small" :current-page="tablePage.currentPage" :page-size="tablePage.pageSize"
          :total="tablePage.total" :page-sizes="[10, 20, 100, 1000, { label: '全量数据', value: 1000000 }]"
          :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
          @page-change="currentChangeHandle">
        </vxe-pager>
      </div>
    </div>
    <ProjectRecordsForm ref="projectRecordsForm" @refreshList="refreshList"></ProjectRecordsForm>
    <ContractNameForm ref="contractNameForm"></ContractNameForm>
    <ProjectRecordsAddForm ref="projectRecordsAddForm" @refreshList="refreshList"></ProjectRecordsAddForm>
    <CwProjectBusinessTypeListForm ref="cwProjectBusinessTypeListForm"></CwProjectBusinessTypeListForm>
    <user-select1 ref="userSelect1" @doSubmit="selectUser1"></user-select1>
    <user-select2 ref="userSelect2" @doSubmit="selectUser2"></user-select2>
    <user-select3 ref="userSelect3" @doSubmit="selectUser3"></user-select3>
    <ProjectRecordsListImport ref="projectRecordsListImport" @refreshDataList="refreshList"></ProjectRecordsListImport>
  </div>
</template>

<script>
// import UserSelect2 from '@/components/userSelect'
import projectRecordsService from '@/api/cw/projectRecords/ProjectRecordsService'
import taskService from '@/api/flowable/TaskService'
import processService from '@/api/flowable/ProcessService'
import ProjectRecordsForm from './ProjectRecordsForm'
import pick from 'lodash.pick'
import userService from '@/api/sys/UserService'
import UserSelect from '@/views/cw/workClientInfo/clientUserSelect'
import ContractNameForm from '../workContract/ContractNameForm'
import ProjectRecordsAddForm from './ProjectRecordsAddForm'
import SelectTree from '@/components/treeSelect/treeSelect.vue'
import UserSelect1 from '@/views/utils/UserTreeSelectBySignatureScribe'
import UserSelect2 from '@/views/utils/UserTreeSelectBySignatureScribe'
import UserSelect3 from '@/views/utils/UserTreeSelect'
import ProjectRecordsListImport from './ProjectRecordsListImport'
export default {
  data() {
    return {
      searchVisible: true,
      showHideItem: false,
      showHideIcon: 'el-icon-arrow-down',
      showHideName: '展示',
      searchForm: {
        projectMasterName: '',
        projectNumber: '',
        businessType: '',
        projectName: '',
        createDates: [],
        status: '',
        realHeaderName: '',
        createBy: {
          name: ''
        },
        cwReportType: '', //报告类型
        cwReportDates: [], // 报告日期
        projectClassification: '', //项目分类
        reportType: '' //报备类型
      },
      dataList: [],
      tablePage: {
        total: 0,
        currentPage: 1,
        pageSize: 10,
        orders: []
      },
      tableKey: '',
      loading: false,
      processDefinitionAuditId: '',
      procDefAuditKey: '',
      isAdmin: false,
      haveProjectIds: ''
    }
  },
  created() {
  },
  components: {
    ProjectRecordsForm,
    UserSelect,
    ContractNameForm,
    ProjectRecordsAddForm,
    UserSelect2,
    SelectTree,
    UserSelect1,
    UserSelect3,
    ProjectRecordsListImport
  },
  computed: {
    userName() {
      return this.$store.state.user.name
    },
    user() {
      this.createName = this.$store.state.user.name
      return this.$store.state.user
    }
  },
  mounted() {
    this.$nextTick(() => {
      //将表格和工具栏进行关联
      const $table = this.$refs.projectTable;
      const $toolbar = this.$refs.toolbarRef;
      $table.connect($toolbar);
    })
    this.refreshList()
  },
  activated() {
    this.refreshList()
  },
  methods: {
    // 项目导入
    projectImport() {
      this.$refs.projectRecordsListImport.init()
    },
    showHide() {
      if (this.showHideItem === false) {
        this.showHideItem = true
        this.showHideIcon = 'el-icon-arrow-up'
        this.showHideName = '隐藏'
      } else {
        this.showHideItem = false
        this.showHideIcon = 'el-icon-arrow-down'
        this.showHideName = '展示'
      }
    },
    // 新增
    add() {
      this.$refs.projectRecordsAddForm.init('add', 'false')
    },
    // 修改
    edit(id) {
      id = id || this.$refs.projectTable.getCheckboxRecords().map(item => {
        return item.id
      })[0]
      this.$refs.projectRecordsAddForm.init('edit', id)
    },
    // 查看
    view(id) {
      this.$refs.projectRecordsForm.init('view', id)
    },
    viewContract(id) {
      this.$refs.contractNameForm.init('view', id)
    },
    // 查询当前用户是否是管理员用户
    checkIsAdmin() {
      userService.is().then((data) => {
        console.log(data)
        this.isAdmin = data
      })
    },
    // 获取数据列表
    refreshList() {
      this.loading = true
      projectRecordsService.list({
        'current': this.tablePage.currentPage,
        'size': this.tablePage.pageSize,
        'orders': this.tablePage.orders,
        ...this.searchForm
      }).then((data) => {
        projectRecordsService.getHaveProjectIds().then((data) => {
          if (this.commonJS.isNotEmpty(data)) {
            this.haveProjectIds = data.map(i => {
              if (this.commonJS.isNotEmpty(i)) {
                return i
              }
            }).join(',')
          }
        })
        this.dataList = data.records
        this.tablePage.total = data.total
        // this.tableKey = Math.random()
        this.loading = false
      })
      this.checkIsAdmin()
      processService.getByName('财务-项目登记').then((data) => {
        if (!this.commonJS.isEmpty(data.id)) {
          this.processDefinitionAuditId = data.id
          this.procDefAuditKey = data.key
        }
      })
    },
    // 当前页
    currentChangeHandle({ currentPage, pageSize }) {
      this.tablePage.currentPage = currentPage
      this.tablePage.pageSize = pageSize
      this.refreshList()
    },
    // 排序
    sortChangeHandle(column) {
      this.tablePage.orders = []
      if (column.order != null) {
        this.tablePage.orders.push({ column: this.$utils.toLine(column.property), asc: column.order === 'asc' })
      }
      this.refreshList()
    },
    // 删除
    del(id) {
      let ids = id || this.$refs.projectTable.getCheckboxRecords().map(item => {
        return item.id
      }).join(',')
      this.$confirm(`确定删除所选项吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        projectRecordsService.delete(ids).then((data) => {
          if (data === '删除成功') {
            this.$message.success(data)
          } else {
            this.$message.error(data)
          }
          this.refreshList()
          this.loading = false
        })
      })
    },
    resetSearch() {
      this.$refs.searchForm.resetFields()
      this.refreshList()
    },
    start() {
      // 读取流程表单
      let tabTitle = `发起流程【项目登记】`
      let processTitle = `${this.userName} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了 [项目登记]`
      taskService.getTaskDef({
        procDefId: this.processDefinitionAuditId,
        status: 'startAndHold'
      }).then((data) => {
        this.$router.push({
          path: '/flowable/task/TaskForm',
          query: {
            ...pick(data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title'),
            procDefId: this.processDefinitionAuditId,
            procDefKey: this.procDefAuditKey,
            status: 'startAndHold',
            title: tabTitle,
            formType: data.formType,
            formUrl: data.formUrl,
            formTitle: processTitle,
            businessId: 'false',
            isShow: false,
            routePath: '/cw/projectRecords/ProjectRecordsList'
          }
        })
      })
    },
    // 发起项目登记
    push(row) {
      // 读取流程表单
      let title = `发起流程【项目登记】`
      let processTitle = `${this.userName} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了[项目登记]`
      let status = 'startAndHold'
      if (row.status === '3') {
        status = 'startAndClose'
      } else if (row.status === '4') {
        status = 'reapplyFlag'
      }
      taskService.getTaskDef({
        procDefId: this.processDefinitionAuditId,
        businessId: row.id,
        businessTable: 'cw_project_records'
      }).then((data) => {
        this.$router.push({
          path: '/flowable/task/TaskForm',
          query: {
            ...pick(data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title'),
            procDefId: this.processDefinitionAuditId,
            procDefKey: this.procDefAuditKey,
            title: title,
            formType: data.formType,
            formUrl: data.formUrl,
            formTitle: processTitle,
            businessTable: 'cw_project_records',
            businessId: row.id,
            isShow: 'false',
            status: status,
            routePath: '/cw/projectRecords/ProjectRecordsList'
          }
        })
      })
    },
    // 查看项目登记流程结果
    detail(row) {
      if (row.status !== '0' && row.status !== '1') {
        // eslint-disable-next-line eqeqeq
        taskService.getTaskDef({
          procInsId: row.procInsId,
          procDefId: this.processDefinitionAuditId
        }).then((data) => {
          this.$router.push({
            path: '/flowable/task/TaskFormDetail',
            query: {
              ...pick(data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title'),
              isShow: 'false',
              readOnly: true,
              title: '项目登记' + '流程详情',
              formTitle: '项目登记' + '流程详情',
              businessId: row.id,
              status: 'reback'
            }
          })
        })
      }
    },
    // 撤回项目登记
    reback(row) {
      this.$confirm(`确定要撤回该申请吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await projectRecordsService.queryById(row.id).then((data) => {
          if (data.status !== '2') { // status的值不等于“审核中”，就弹出提示
            this.$message.error('数据已发生改变或不存在，请刷新数据')
            this.refreshList()
          } else {
            processService.revokeProcIns(row.procInsId).then((data) => {
              let form = { status: '3', id: row.id }
              projectRecordsService.updateStatusById(form)
              this.$message.success(data)
              this.refreshList()
            })
          }
        })
      })
    },
    // 自定义服务端导出
    exportMethod({ options }) {
      // 传给服务端的参数
      const params = {
        'current': this.tablePage.currentPage,
        'size': this.tablePage.pageSize,
        'orders': this.tablePage.orders,
        ...this.searchForm,
        filename: options.filename,
        sheetName: options.sheetName,
        isHeader: options.isHeader,
        original: options.original,
        mode: options.mode,
        selectIds: options.mode === 'selected' ? options.data.map(item => item.id) : [],
        exportFields: options.columns.map(column => column.property)
      }
      return projectRecordsService.exportFile(params).then((res) => {
        // 将二进制流文件写入excel表，以下为重要步骤
        this.$utils.downloadExcel(res, options.filename + '.xls')
      }).catch(function (err) {
        if (err.response) {
          console.log(err.response)
        }
      })
    },
    openUserDia1() {
      this.$refs.userSelect1.init()
    },
    selectUser1(user) {
      console.log(user[0].name)
      this.searchForm.projectMasterName = user[0].name
    },
    openUserDia2() {
      this.$refs.userSelect2.init()
    },
    selectUser2(user) {
      console.log(user[0].name)
      this.searchForm.realHeaderName = user[0].name
    },
    openUserDia3() {
      this.$refs.userSelect3.init()
    },
    selectUser3(user) {
      console.log(user[0].name)
      this.searchForm.createBy.name = user[0].name
    },
  }
}
</script>
