<template>
  <div class="page">
    <el-form :inline="true" class="query-form m-b-10" v-if="searchVisible" ref="searchForm" :model="searchForm" @keyup.enter.native="refreshList()" @submit.native.prevent>
      <!-- 搜索框-->
      <el-form-item label="客户名称" prop="name">
        <el-input v-model="searchForm.name" placeholder="请输入客户名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="合同名称" prop="contractName">
        <el-input v-model="searchForm.contractName" placeholder="请输入合同名称" clearable></el-input>
      </el-form-item>
      <el-form-item v-if="showHideItem" label="状态" prop="status">
        <el-select v-model="searchForm.status" placeholder="请选择" style="width:100%;">
          <el-option
            v-for="item in $dictUtils.getDictList('cw_status')"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="showHideItem" label="合同生效日期" prop="effectiveDates">
        <el-date-picker
          placement="bottom-start"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          v-model="searchForm.effectiveDates"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </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}" custom>
        <template #buttons>
          <el-button v-if="hasPermission('contract:add')" type="primary" icon="el-icon-plus" @click="start()">新建</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"
          ref="clientTable"
          show-header-overflow
          show-overflow
          highlight-hover-row
          :menu-config="{}"
          @sort-change="sortChangeHandle"
          :sort-config="{remote:true}"
          :data="dataList"
          :checkbox-config="{}">
          <vxe-column type="seq" width="60" title="序号"></vxe-column>
          <vxe-column min-width="160" align="center" title="合同编号" field="contractNo"></vxe-column>
          <vxe-column min-width="160" align="center" title="合同名称" field="contractName">
            <template slot-scope="scope">
              <el-link  type="primary" :underline="false" v-if="hasPermission('material:list')" @click="view(scope.row.id)">{{scope.row.contractName}}</el-link>
              <el-link  type="primary" :underline="false" v-else-if="hasPermission('material:list')"  @click="view(scope.row.id,)">{{scope.row.contractName}}</el-link>
              <span v-else>{{scope.row.contractName}}</span>
            </template>
          </vxe-column>
          <vxe-column min-width="160" align="center" title="客户名称" field="name"></vxe-column>
          <vxe-column min-width="160" align="center" title="统一社会信用代码" field="uscCode"></vxe-column>
          <vxe-column min-width="160" align="center" title="详细地址" field="address"></vxe-column>
          <vxe-column min-width="160" align="center" title="合同生效日期" field="effectiveDate"></vxe-column>
          <vxe-column min-width="160" align="center" title="合同终止日期" field="endTime"></vxe-column>
          <vxe-column  min-width="150px" align="center" fixed="right" title="状态" field="status" >
            <template #default="scope">
              <el-button  @click="detail(scope.row)" effect="dark"
                          :type="$dictUtils.getDictLabel('cw_status_flag', scope.row.status, '-')">
                {{$dictUtils.getDictLabel("cw_status", scope.row.status, '-')}}
              </el-button>
            </template>
          </vxe-column>

          <vxe-column title="操作" width="150px" fixed="right" align="center">
            <template  slot-scope="scope">
              <el-button v-if="hasPermission('contract:edit')&&scope.row.createBy === $store.state.user.id&&(scope.row.status==='1'||scope.row.status==='3')" type="text"  size="small" @click="push(scope.row)">修改</el-button>
              <el-button v-else-if="hasPermission('contract:edit')&&isAdmin&&(scope.row.status==='1'||scope.row.status==='3'||scope.row.status==='4'||scope.row.status==='5')" type="text"  size="small" @click="edit(scope.row.id)">修改</el-button>
              <el-button v-if="hasPermission('contract:edit')&&scope.row.createBy === $store.state.user.id&&scope.row.status==='2'" type="text"  size="small" @click="reback(scope.row)">撤回</el-button>
              <el-button v-if="hasPermission('contract:del')&&scope.row.createBy === $store.state.user.id&&(scope.row.status==='1'||scope.row.status==='3')" type="text"   size="small" @click="del(scope.row.id)">删除</el-button>
              <el-button v-else-if="hasPermission('contract:del')&&isAdmin&&(scope.row.status==='1'||scope.row.status==='3'||scope.row.status==='4'||scope.row.status==='5')" type="text"   size="small" @click="del(scope.row.id)">删除</el-button>
            </template>
          </vxe-column>
        </vxe-table>
        <vxe-pager
          background
          :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>
        <UpdateContractInfoForm ref="updateContractInfoForm" @refreshDataList="refreshList"></UpdateContractInfoForm>
      </div>
    </div>
  </div>
</template>

<script>
  import UpdateContractInfoForm from './UpdateContractInfoForm'
  import MaterialManagementService from '@/api/materialManagement/MaterialManagementService'
  import ContractService from '@/api/materialManagement/ContractService'
  import taskService from '@/api/flowable/taskService'
  import processService from '@/api/flowable/processService'
  import pick from 'lodash.pick'
  import userService from '@/api/sys/userService'
  export default {
    data () {
      return {
		  searchVisible: true,
        showHideItem: false,
        showHideIcon: 'el-icon-arrow-down',
        showHideName: '展示',
        num: 0,
        searchForm: {
          contractName: '',
          name: '',
          handledBy: '',
          handledByOffice: '',
          status: '',
          effectiveDates: [],
          procurementType: '',
          createBy: ''
        },
        dataList: [],
        tablePage: {
          total: 0,
          currentPage: 1,
          pageSize: 10,
          orders: []
        },
        tableKey: '',
        loading: false,
        processDefinitionAuditId: '',
        procDefAuditKey: '',
        isAdmin: false,
        create: ''
      }
    },
    materialManagementService: null,
    contractService: null,
    created () {
      this.materialManagementService = new MaterialManagementService()
      this.contractService = new ContractService()
    },
    components: {
      UpdateContractInfoForm,
    },
    computed: {
      userName () {
        return this.$store.state.user.name
      },
      user () {
        this.createName = this.$store.state.user.name
        return this.$store.state.user
      }
    },
    mounted () {
      this.refreshList()
    },
    activated () {
      this.refreshList()
    },
    methods: {
      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.reportManagementForm.init('add', '')
      },
      // 修改
      edit (id) {
        id = id || this.$refs.clientTable.getCheckboxRecords().map(item => {
          return item.id
        })[0]
        this.$refs.updateContractInfoForm.init('edit', id)
      },
      // 查看
      view (id) {
        this.$refs.updateContractInfoForm.init('view', id)
      },
      // 查询当前用户是否是管理员用户
      checkIsAdmin () {
        userService.is().then((data) => {
          this.isAdmin = data
        })
      },
      // 获取数据列表
      refreshList () {
        this.loading = true
        this.contractService.list({
          'current': this.tablePage.currentPage,
          'size': this.tablePage.pageSize,
          'orders': this.tablePage.orders,
          ...this.searchForm
        }).then((data) => {
          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.clientTable.getCheckboxRecords().map(item => {
          return item.id
        }).join(',')
        this.$confirm(`确定删除所选项吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          this.contractService.remove(ids).then((data) => {
            this.$message.success(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: '/materialManagement/contract/ContractList'
              }
            })
          })
      },
      // 发起物资管理-合同申请
      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: 'material_management_pruchase_request_basics'}).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: 'material_management_pruchase_request_basics',
                businessId: row.id,
                isShow: 'false',
                status: status,
                routePath: '/materialManagement/contract/ContractList'
              }
            })
          })
      },
      // 查看客户登记流程结果
      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 this.contractService.findById(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}
                this.contractService.updateStatusById(form)
                this.$message.success(data)
                this.refreshList()
              })
            }
          })
        })
      }
    }
  }
</script>
