<template>
  <div class="page">
    <el-form size="small" :inline="true" class="query-form" ref="searchForm" :model="searchForm" @keyup.enter.native="refreshList()" @submit.native.prevent>
      <!-- 搜索框-->
      <el-form-item label="合同编号" prop="contractNo">
        <el-input size="small" v-model="searchForm.contractNo" placeholder="请输入客户名称" clearable></el-input>
      </el-form-item>

      <el-form-item label="合同名称" prop="contractName">
        <el-input size="small" v-model="searchForm.contractName" placeholder="请输入合同名称" clearable></el-input>
      </el-form-item>

      <el-form-item label="合同金额" prop="contractAmounts">
        <InputNumber :disabled="false" :precision="num" v-model="searchForm.contractAmounts"></InputNumber>
      </el-form-item>

      <el-form-item label="签约时间" prop="contractDates">
        <el-date-picker
          placement="bottom-start"
          v-model="searchForm.contractDates"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="创建人" prop="createBy">
        <SelectUserTree
          ref="companyTree"
          :props="{
                  value: 'id',             // ID字段名
                  label: 'name',         // 显示名称
                  children: 'children'    // 子级字段名
                }"
          :url="`/sys/user/treeUserDataAllOffice?type=2`"
          :value="searchForm.createBy"
          :clearable="true"
          :accordion="true"
          @getValue="(value) => {searchForm.createBy=value}"/>
      </el-form-item>

      <el-form-item  prop="department" label="所属部门">
        <SelectTree
          ref="officeTree"
          :props="{
                  value: 'id',             // ID字段名
                  label: 'name',         // 显示名称
                  children: 'children'    // 子级字段名
                }"

          :url="`/sys/office/treeData?type=2`"
          :value="searchForm.department"
          :accordion="true"
          @getValue="(value) => {searchForm.department=value}"/>
      </el-form-item>

      <el-form-item 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 label="归档状态" prop="filedType">
        <el-select v-model="searchForm.filedType" placeholder="请选择" style="width:100%;">
          <el-option
            v-for="item in $dictUtils.getDictList('filed_type')"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="refreshList()" size="small" icon="el-icon-search">查询</el-button>
        <el-button @click="resetSearch()" size="small" icon="el-icon-refresh-right">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="bg-white top">
      <vxe-toolbar :refresh="{query: refreshList}" import export print custom>
        <template #buttons>
          <el-button v-if="hasPermission('cw:workContract:add')" type="primary" size="small" icon="el-icon-plus" @click="add()">新建</el-button>
          <el-button v-if="hasPermission('cw:workContract:del')" type="danger"   size="small" icon="el-icon-delete" @click="del()" plain>删除</el-button>
        </template>
      </vxe-toolbar>
      <div style="height: calc(100% - 80px);">
        <vxe-table
          border="inner"
          auto-resize
          resizable
          height="auto"
          :loading="loading"
          size="small"
          ref="workContractTable"
          show-header-overflow
          show-overflow
          highlight-hover-row
          :menu-config="{}"
          :print-config="{}"
          @sort-change="sortChangeHandle"
          :sort-config="{remote:true}"
          :data="dataList"
          :checkbox-config="{}">
          <vxe-column type="seq" width="60" title="序号"></vxe-column>
          <vxe-column type="checkbox" width="40px"></vxe-column>

          <vxe-column width="200px" title="合同编号" field="contractNo"></vxe-column>
          <vxe-column width="200px" title="合同名称" field="contractName">
            <template slot-scope="scope">
              <el-link  type="primary" :underline="false" v-if="hasPermission('cw:workContract:edit')" @click="view(scope.row.id)">{{scope.row.contractName}}</el-link>
              <el-link  type="primary" :underline="false" v-else-if="hasPermission('cw:workContract:view')" @click="view(scope.row.id)">{{scope.row.contractName}}</el-link>
              <span v-else>{{scope.row.contractName}}</span>
            </template>
          </vxe-column>
          <vxe-column width="200px" title="签约日期" field="signingDate"></vxe-column>
          <vxe-column width="200px" title="合同金额(元)" field="contractAmount"></vxe-column>
          <vxe-column width="200px" title="所属部门" field="department"></vxe-column>
          <vxe-column width="200px" title="创建人" field="createBy"></vxe-column>
          <vxe-column width="200px" title="创建日期" field="createDate"></vxe-column>
          <vxe-column width="200px" title="状态" field="status">
            <template slot-scope="scope">
              <el-button  type="text" @click="detail(scope.row)" :type="$dictUtils.getDictLabel('cw_status_flag', scope.row.status, '-')" effect="dark" size="mini">{{$dictUtils.getDictLabel("cw_status", scope.row.status, '-')}} </el-button>
            </template>
          </vxe-column>
          <vxe-column width="200px" title="归档状态" field="filedType">
            <template slot-scope="scope">
              <el-button  type="text" @click="detailFiled(scope.row)" :type="$dictUtils.getDictLabel('filed_type_status', scope.row.filedType, '-')" effect="dark" size="mini">{{$dictUtils.getDictLabel("filed_type", scope.row.filedType, '未归档')}} </el-button>
            </template>
          </vxe-column>


          <vxe-column title="操作" width="200px" fixed="right" align="center">
            <template  slot-scope="scope">
              <el-button v-if="hasPermission('cw:workContract:view')" type="text" size="small" @click="view(scope.row.id)">查看</el-button>
              <el-button v-if="hasPermission('cw:workContract:edit') && scope.row.status !== '2' && scope.row.status !== '5' && scope.row.createId === create" type="text" size="small" @click="edit(scope.row)">修改</el-button>
              <el-button v-if="hasPermission('cw:workContract:edit') && scope.row.status === '5' && isAdmin" type="text" size="small" @click="editForm(scope.row.id)">修改</el-button>
              <el-button v-if="hasPermission('cw:workContract:del') && (scope.row.status === '1' || scope.row.status === '3' || scope.row.status === '4')  && scope.row.createId === create" type="text" size="small" @click="del(scope.row.id)">删除</el-button>
              <el-button v-if="hasPermission('cw:workContract:back') && scope.row.status === '2'" type="text" size="small" @click="reback(scope.row)">撤回</el-button>
              <el-button v-if="hasPermission('cw:workContract:filed') && scope.row.status === '5' && scope.row.createId === create && (scope.row.filedType === '0' || scope.row.filedType === undefined)" type="text" size="small" @click="filed(scope.row.id)">归档</el-button>
              <!--归档暂存修改-->
              <el-button v-if="hasPermission('cw:workContract:filed') && scope.row.status === '5' && scope.row.createId === create && scope.row.filedType === '1'" type="text" size="small" @click="filed(scope.row.id)">修改</el-button>
              <!--归档撤回驳回修改-->
              <el-button v-if="hasPermission('cw:workContract:filed') && scope.row.status === '5' && scope.row.createId === create && (scope.row.filedType === '3' || scope.row.filedType === '4')" type="text" size="small" @click="filedAndClose(scope.row.id)">修改</el-button>
              <!--归档撤回-->
              <el-button v-if="hasPermission('cw:workContract:back') && scope.row.status === '5' && scope.row.filedType === '2'" type="text"  size="small" @click="rebackFiled(scope.row)">撤回</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>
    <!-- 弹窗, 新增 / 修改 -->
    <ContractNameForm ref="contractNameForm"></ContractNameForm>
    <WorkClientForm ref="workClientForm" @refreshDataList="refreshList"></WorkClientForm>
    <WorkContractBorrowMessageForm ref="workContractBorrowMessageForm" @refreshDataList="refreshList"></WorkContractBorrowMessageForm>
  </div>
</template>

<script>
  import InputNumber from './InputNumber.vue'
  import ContractNameForm from './ContractNameForm'
  import WorkClientForm from '../../sys/workClient/WorkClientForm'
  import WorkContractBorrowMessageForm from './WorkContractBorrowMessageForm'
  // import WorkContractService from '@/api/sys/WorkContractService'
  import ContractInfoService from '../../../../api/cw/workContract/ContractInfoService'
  // import WorkContractFileService from '@/api/sys/WorkContractFileService'
  import ContractFileService from '@/api/cw/workContract/ContractFileService'
  import WorkContractBorrowService from '@/api/sys/WorkContractBorrowService'
  import SelectUserTree from '@/views/modules/utils/treeUserSelect'
  import TaskService from '@/api/flowable/TaskService'
  import ProcessService from '@/api/flowable/ProcessService'
  import pick from 'lodash.pick'
  import UserService from '@/api/sys/UserService'
  import SelectTree from '@/components/treeSelect/treeSelect.vue'
  export default {
    data () {
      return {
        visible: false,
        num: 0,
        searchForm: {
          contractNo: '',
          contractName: '',
          contractAmount: '',
          contractDates: [],
          type: '',
          filedType: '',
          contractAmounts: [],
          createBy: '',
          createId: '',
          department: '',
          status: '',
          procInsId: '',
          processDefinitionId: ''
        },
        dataList: [],
        tablePage: {
          total: 0,
          currentPage: 1,
          pageSize: 10,
          orders: []
        },
        processDefinitionId: '',
        procDefKey: '',
        loading: false,
        create: '',
        isAdmin: false
      }
    },
    // workContractService: null,
    contractInfoService: null,
    contractFileService: null,
    workContractBorrowService: null,
    taskService: null,
    processService: null,
    userService: null,
    created () {
      // this.workContractService = new WorkContractService()
      this.contractInfoService = new ContractInfoService()
      this.contractFileService = new ContractFileService()
      this.workContractBorrowService = new WorkContractBorrowService()
      this.taskService = new TaskService()
      this.processService = new ProcessService()
      this.userService = new UserService()
    },
    components: {
      InputNumber,
      ContractNameForm,
      WorkClientForm,
      WorkContractBorrowMessageForm,
      SelectUserTree,
      SelectTree
    },
    activated () {
      this.is()
      this.refreshList()
    },
    computed: {
      userName () {
        return JSON.parse(localStorage.getItem('user')).name
      },
      user () {
        this.create = JSON.parse(localStorage.getItem('user')).id
        console.log('createId', this.create)
        return JSON.parse(localStorage.getItem('user'))
      }
    },

    methods: {
      // 获取数据列表
      refreshList () {
        console.log('user', this.user)
        this.loading = true
        this.contractInfoService.list({
          'current': this.tablePage.currentPage,
          'size': this.tablePage.pageSize,
          'orders': this.tablePage.orders,
          'itemType': '1',
          ...this.searchForm
        }).then(({data}) => {
          this.dataList = data.records
          this.tablePage.total = data.total
          this.loading = false
        })
        this.processService.getByName('财务-合同登记').then(({data}) => {
          if (!this.commonJS.isEmpty(data.id)) {
            this.processDefinitionId = data.id
            this.procDefKey = 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()
      },
      // 新增
      add () {
        this.start()
      },
      // 详情
      detail (row) {
        // eslint-disable-next-line eqeqeq
        if (!this.commonJS.isEmpty(row.status) && row.status != '1') {
          this.taskService.getTaskDef({
            procInsId: row.procInsId,
            procDefId: row.processDefinitionId
          }).then(({data}) => {
            this.$router.push({
              path: '/flowable/task/TaskFormDetail',
              query: {
                readOnly: true,
                title: '流程详情',
                formTitle: '流程详情',
                businessId: row.id,
                ...pick(data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title', 'businessId')}
            })
          })
        }
      },
      // 修改
      edit (row) {
        if (row.status === '3' || row.status === '4') {
          this.editWithClose(row)
        } else {
          this.editWithHold(row)
        }
      },
      // 管理员修改
      editForm (id) {
        id = id || this.$refs.workClientTable.getCheckboxRecords().map(item => {
          return item.id
        })[0]
        this.$refs.contractNameForm.init('edit', id)
      },
      // 查看
      view (id) {
        this.$refs.contractNameForm.init('view', id)
      },
      // 客户信息查看
      viewInfo (id) {
        this.$refs.workClientForm.init('view', id)
      },
      // 删除
      del (id) {
        let ids = id || this.$refs.workContractTable.getCheckboxRecords().map(item => {
          return item.id
        }).join(',')
        this.$confirm(`确定删除所选项吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          this.contractInfoService.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')} 发起了 [财务-合同登记]`
        this.taskService.getTaskDef({ procDefId: this.processDefinitionId,
          status: 'startAndHold'}).then((data) => {
            this.$router.push({
              path: '/flowable/task/TaskForm',
              query: {
                procDefId: this.processDefinitionId,
                procDefKey: this.procDefKey,
                status: 'startAndHold',
                title: tabTitle,
                formType: data.data.formType,
                formUrl: data.data.formUrl,
                formTitle: processTitle,
                businessId: 'false',
                isShow: false,
                routePath: '/cw/workContract/ContractRegistration'
              }
            })
          })
      },
      editWithHold (row) {
        // 读取流程表单
        let tabTitle = `发起流程【财务-合同登记】`
        let processTitle = `${this.userName} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了 [财务-合同登记]`
        this.taskService.getTaskDef({ procDefId: this.processDefinitionId,
          businessId: row.id,
          businessTable: 'cw_work_contract_info',
          status: 'startAndHold'}).then((data) => {
            this.$router.push({
              path: '/flowable/task/TaskForm',
              query: {
                procDefId: this.processDefinitionId,
                procDefKey: this.procDefKey,
                status: 'startAndHold',
                title: tabTitle,
                formType: data.data.formType,
                formUrl: data.data.formUrl,
                formTitle: processTitle,
                businessTable: 'cw_work_contract_info',
                businessId: row.id,
                isShow: false,
                routePath: '/cw/workContract/ContractRegistration'
              }
            })
          })
      },
      editWithClose (row) {
        // 读取流程表单
        let tabTitle = `发起流程【财务-合同登记】`
        let processTitle = `${this.userName} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了 [财务-合同登记]`
        this.taskService.getTaskDef({ procDefId: this.processDefinitionId,
          businessId: row.id,
          businessTable: 'work_contract_info',
          status: 'startAndClose'
        }).then((data) => {
          this.$router.push({
            path: '/flowable/task/TaskForm',
            query: {
              procDefId: this.processDefinitionId,
              procDefKey: this.procDefKey,
              status: 'startAndClose',
              title: tabTitle,
              formType: data.data.formType,
              formUrl: data.data.formUrl,
              formTitle: processTitle,
              businessTable: 'work_contract_info',
              businessId: row.id,
              isShow: false,
              routePath: '/cw/workContract/ContractRegistration'
            }
          })
        })
      },
      reback (row) {
        // console.log('row', row.procInsId)
        this.$confirm(`确定撤回流程吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.processService.revokeProcIns(row.procInsId).then(({data}) => {
            // console.log('updateStatusById')
            let form = {status: '3', id: row.id}
            this.updateStatusById(form, 'reback')
            this.$message.success(data)
            this.refreshList()
          })
        })
      },
      rebackFiled (row) {
        // console.log('row.taskFiledProcInsId' + row.taskFiledProcInsId)
        this.$confirm(`确定撤回流程吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.processService.revokeProcIns(row.taskFiledProcInsId).then(({data}) => {
            // let form = {filedType: '3', id: row.id}
            this.updateStatusById(row, 'rebackFiled')
            this.$message.success(data)
            this.refreshList()
          })
          // this.taskService.backNodes(row.taskFiledId).then(({data}) => {
          //   let backNodes = data
          //   if (backNodes.length > 0) {
          //     let backTaskDefKey = backNodes[0].taskDefKey
          //     this.taskService.back({
          //       taskId: row.taskFiledId,
          //       backTaskDefKey: backTaskDefKey,
          //       isShow: false,
          //       ...this.auditForm
          //     }).then(({data}) => {
          //       this.updateStatusById(row, 'rebackFiled')
          //       this.$message.success('回退成功')
          //     })
          //   }
          // })
        })
      },
      updateStatusById (row, type) {
        // console.log('updateStatusByIdupdateStatusById')
        // console.log(type)
        if (type === 'agree') {
          row.status = '5'
          this.contractInfoService.updateStatusById(row)
        }
        if (type === 'reject') {
          row.status = '4'
          this.contractInfoService.updateStatusById(row)
        }
        if (type === 'reback') {
          row.status = '3'
          this.contractInfoService.updateStatusById(row)
        }
        if (type === 'rebackFiled') {
          row.filedType = '3'
          this.contractFileService.updateStatusById(row)
        }
        if (type === 'rebackBorrow') {
          row.borrowType = '0'
          this.workContractBorrowService.updateStatusByContractInfoId(row).then(() => {
            this.workContractBorrowService.deleteById(row.id)
          })
        }
        if (type === 'retureBorrow') {
          row.borrowType = '0'
          this.workContractBorrowService.updateStatusByContractInfoId(row).then(() => {
            row.type = 'reture'
            row.borrowType = '5'
            this.workContractBorrowService.updateMessageStatusById(row)
          })
        }
      },
      is () {
        this.userService.is().then(({data}) => {
          this.isAdmin = data
        })
      },
      // 归档
      filed (id) {
        this.processService.getByName('财务-合同登记归档').then(({data}) => {
          if (!this.commonJS.isEmpty(data.id)) {
            // console.log('data', data)
            // 读取流程表单
            let tabTitle = `发起流程【财务-合同登记归档】`
            let processTitle = `${this.userName} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了 [财务-合同登记归档]`
            this.taskService.getTaskDef({ procDefId: data.id,
              businessId: id,
              businessTable: 'cw_work_contract_file',
              status: 'startAndHoldFiled'}).then((reture) => {
                this.$router.push({
                  path: '/flowable/task/TaskForm',
                  query: {
                    procDefId: data.id,
                    procDefKey: data.key,
                    status: 'startAndHoldFiled',
                    title: tabTitle,
                    formType: reture.data.formType,
                    formUrl: reture.data.formUrl,
                    formTitle: processTitle,
                    businessTable: 'cw_work_contract_file',
                    businessId: id,
                    isShow: false,
                    routePath: '/cw/workContract/ContractRegistration'
                  }
                })
              })
          }
        })
      },
      // 归档
      filedAndClose (id) {
        this.processService.getByName('财务-合同登记归档').then(({data}) => {
          if (!this.commonJS.isEmpty(data.id)) {
            // console.log('data', data)
            // 读取流程表单
            let tabTitle = `发起流程【财务-合同登记归档】`
            let processTitle = `${this.userName} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了 [财务-合同登记归档]`
            this.taskService.getTaskDef({ procDefId: data.id,
              businessId: id,
              businessTable: 'cw_work_contract_file',
              status: 'startAndCloseFiled'}).then((reture) => {
                this.$router.push({
                  path: '/flowable/task/TaskForm',
                  query: {
                    procDefId: data.id,
                    procDefKey: data.key,
                    status: 'startAndCloseFiled',
                    title: tabTitle,
                    formType: reture.data.formType,
                    formUrl: reture.data.formUrl,
                    formTitle: processTitle,
                    businessTable: 'cw_work_contract_file',
                    businessId: id,
                    isShow: false,
                    routePath: '/cw/workContract/ContractRegistration'
                  }
                })
              })
          }
        })
      },
      // 归档详情
      detailFiled (row) {
        // console.log('row.id', row.id)
        // eslint-disable-next-line eqeqeq
        if (!this.commonJS.isEmpty(row.filedType) && row.filedType != '1') {
          this.contractFileService.findByContractInfoId(row.id).then(({data}) => {
            if (!this.commonJS.isEmpty(data.id)) {
              // console.log('data', data)
              this.taskService.getTaskDef({
                procInsId: data.procInsId,
                procDefId: data.processDefinitionId
              }).then(({data}) => {
                this.$router.push({
                  path: '/flowable/task/TaskFormDetail',
                  query: {
                    readOnly: true,
                    title: '归档流程详情',
                    formTitle: '归档流程详情',
                    businessId: row.id,
                    ...pick(data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title')}
                })
              })
            }
          })
        }
      }
    }
  }
</script>
