<!--
 * @Author: liuzhenlin 461480418@qq.ocm
 * @Date: 2023-01-05 11:28:51
 * @LastEditors: wanglj
 * @LastEditTime: 2023-03-22 14:53:09
 * @FilePath: \opms_frontend\src\views\contract\index.vue
-->
<template>
  <div class="contract-container">
    <vab-query-form>
      <vab-query-form-top-panel>
        <el-form :inline="true" label-width="0px" :model="queryForm" @submit.native.prevent>
          <el-form-item prop="contractCode">
            <el-input
              v-model="queryForm.contractCode"
              clearable
              placeholder="合同编号"
              @keyup.enter.native="queryData" />
          </el-form-item>
          <el-form-item prop="contractName">
            <el-input
              v-model="queryForm.contractName"
              clearable
              placeholder="合同名称"
              @keyup.enter.native="queryData" />
          </el-form-item>
          <el-form-item prop="custId">
            <el-input v-model="queryForm.custName" clearable placeholder="客户名称" @keyup.enter.native="queryData" />
          </el-form-item>
          <el-form-item prop="custId">
            <el-input v-model="queryForm.nboName" clearable placeholder="项目名称" @keyup.enter.native="queryData" />
          </el-form-item>
          <el-form-item prop="custId">
            <el-select v-model="queryForm.approStatus" clearable placeholder="审批状态">
              <el-option v-for="(v, k) in approStatusOption" :key="k" :label="v" :value="k" />
            </el-select>
          </el-form-item>
          <el-form-item prop="inchargeName">
            <el-input
              v-model="queryForm.inchargeName"
              clearable
              placeholder="销售工程师"
              @keyup.enter.native="queryData" />
          </el-form-item>
          <el-form-item prop="custProvince">
            <el-select v-model="queryForm.custProvince" clearable placeholder="所在省" value-key="id">
              <el-option v-for="item in provinceOptions" :key="item.id" :label="item.distName" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item prop="custCity">
            <el-select v-model="queryForm.custCity" clearable placeholder="所在市" value-key="id">
              <el-option
                v-for="item in queryForm.custProvince ? queryForm.custProvince.children : []"
                :key="item.id"
                clearable
                :label="item.distName"
                :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item prop="filterDate">
            <el-date-picker
              v-model="queryForm.filterDate"
              end-placeholder="合同签订结束时间"
              range-separator="至"
              start-placeholder="合同签订开始时间"
              style="width: 100%"
              type="daterange"
              value-format="yyyy-MM-dd" />
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" type="primary" @click="queryData">查询</el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-top-panel>
      <vab-query-form-left-panel :span="12">
        <el-button v-permissions="['contract:manage:add']" icon="el-icon-plus" type="primary" @click="handleEdit()">
          新建
        </el-button>
        <el-button
          v-permissions="['contract:manage:transfer']"
          icon="el-icon-refresh"
          type="primary"
          @click="handleTransfer()">
          转移
        </el-button>
        <el-button
          v-permissions="['contract:manage:delete']"
          icon="el-icon-delete"
          type="danger"
          @click="handleDelete()">
          删除
        </el-button>
      </vab-query-form-left-panel>
      <vab-query-form-right-panel :span="12">
        <table-tool :columns="columns" :show-columns.sync="showColumns" table-type="contractTable" />
      </vab-query-form-right-panel>
    </vab-query-form>
    <el-table ref="table" v-loading="listLoading" :data="list" :height="height" @selection-change="setSelectRows">
      <el-table-column align="center" show-overflow-tooltip type="selection" />
      <el-table-column
        v-for="(item, index) in showColumns"
        :key="index"
        align="center"
        :label="item.label"
        :min-width="item.width"
        :prop="item.prop"
        show-overflow-tooltip
        :sortable="item.sortable">
        <template #default="{ row }">
          <el-button
            v-if="item.prop === 'custName' && row.custId != 0"
            class="link-button"
            type="text"
            @click="handleCustDetail(row)">
            {{ row.custName }}
          </el-button>
          <span v-else-if="item.prop === 'contractAmount'">
            {{ formatPrice(row.contractAmount) }}
          </span>
          <span v-else-if="item.prop === 'approStatus'">
            {{ approStatusOption[row.approStatus] }}
          </span>
          <span v-else-if="item.prop === 'productLine'">
            {{ productLineOptions[row.productLine] }}
          </span>
          <span v-else-if="item.label === '合同有效时间'">
            {{ parseTime(row.contractStartTime, '{y}-{m}-{d}') }}~{{ parseTime(row.contractEndTime, '{y}-{m}-{d}') }}
          </span>
          <span v-else-if="item.label === '合同类型'">
            {{ contractOptions[row.contractType] }}
          </span>
          <span v-else-if="item.label === '签订单位类型'">
            {{
              row.signatoryType == '10'
                ? '终端用户'
                : row.signatoryType == '20'
                ? '经销商'
                : row.signatoryType == '30'
                ? '代理商'
                : ''
            }}
          </span>
          <span v-else-if="item.label === '合同签订单位'">
            {{
              row.signatoryType == '10'
                ? row.custName
                : row.signatoryType == '20'
                ? row.distributorName
                : row.signatoryType == '30'
                ? row.distributorName
                : ''
            }}
          </span>
          <span v-else-if="item.label === '合同签订时间'">
            {{ parseTime(row.contractSignTime, '{y}-{m}-{d}') }}
          </span>
          <span v-else-if="item.label === '回款金额'">
            {{ formatPrice(row.collectedAmount) }}
          </span>
          <span v-else-if="item.label === '开票金额'">
            {{ formatPrice(row.invoiceAmount) }}
          </span>
          <el-button
            v-else-if="item.prop === 'contractCode'"
            style="font-size: 14px"
            type="text"
            @click="handleContractDetail(row)">
            {{ row.contractCode }}
          </el-button>
          <span v-else>{{ row[item.prop] }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="110px">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.approStatus == '10'"
            v-permissions="['contract:manage:apply']"
            type="text"
            @click="handleApply(scope.row.id)">
            提交审核
          </el-button>
          <el-button
            v-if="scope.row.approStatus == '10'"
            v-permissions="['contract:manage:edit']"
            type="text"
            @click="handleEdit(scope.row)">
            编辑
          </el-button>
          <el-button v-permissions="['contract:manage:delete']" type="text" @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      :current-page="queryForm.pageNum"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange" />
    <!-- 新增编辑客户弹窗 -->
    <Edit ref="edit" @contractSave="contractSave" />
    <!-- 转移合同 -->
    <Transfer ref="transfer" :contract-id="contractId" @transferSave="contractSave" />
    <ApplyContract ref="applyContract" @refresh="queryData" />
  </div>
</template>

<script>
  import to from 'await-to-js'
  import contractApi from '@/api/contract'
  import Edit from './components/Edit'
  import TableTool from '@/components/table/TableTool'
  import Transfer from './components/Transfer'
  import ApplyContract from './components/ApplyContract'
  import api from '@/api/customer'

  export default {
    name: 'Contract',
    components: {
      Edit,
      TableTool,
      Transfer,
      ApplyContract,
    },
    data() {
      return {
        height: this.$baseTableHeight(2),
        approStatusOption: {
          10: '待提交审核',
          20: '待审核',
          30: '审核已同意',
          40: '审核已拒绝',
          50: '审核已撤销',
        },
        contractId: [], //当前合同id
        listLoading: false,
        layout: 'total, sizes, prev, pager, next, jumper',
        list: [],
        total: 0,
        queryForm: {
          pageNum: 1,
          pageSize: 10,
          contractCode: '', // 合同编号
          contractName: '', //合同名称
          custName: '', // 客户名称  ()
          nboName: '', //项目名称
          approStatus: '', //审批状态
          inchargeName: '', // 负责人(销售工程师)
          custProvinceId: 0,
          custProvince: null,
          custCityId: 0,
          custCity: null,
          filterDate: [],
        },
        provinceOptions: [],
        selectRows: [], //选择的表格数据
        industryOptions: [], //客户行业
        levelOptions: [], //客户级别
        contractOptions: {}, //合同类型
        productLineOptions: {}, //产品线
        // 自定义列表
        showColumns: [],
        columns: [
          {
            label: '合同编号',
            width: '160px',
            prop: 'contractCode',
            sortable: false,
            disableCheck: false,
          },
          {
            label: '合同类型',
            width: '100px',
            prop: 'contractType',
            sortable: false,
            disableCheck: false,
          },
          {
            label: '所在省',
            width: '100px',
            prop: 'custProvince',
            sortable: false,
            disableCheck: false,
          },
          {
            label: '所在市',
            width: '100px',
            prop: 'custCity',
            sortable: false,
            disableCheck: false,
          },
          {
            label: '客户名称',
            width: '280px',
            prop: 'custName',
            sortable: false,
            disableCheck: false,
          },
          {
            label: '产品线',
            prop: 'productLine',
            width: '140px',
          },
          {
            label: '签订单位类型',
            width: '120px',
            prop: 'signatoryType',
            sortable: false,
            disableCheck: false,
          },
          {
            label: '合同签订单位',
            width: '120px',
            prop: 'distributorName',
            sortable: false,
            disableCheck: false,
          },
          {
            label: '合同签订时间',
            width: '120px',
            prop: 'contractSignTime',
            sortable: false,
            disableCheck: false,
          },
          {
            label: '合同有效时间',
            width: '200px',
            prop: 'contractStartTime',
            sortable: false,
            disableCheck: false,
          },
          {
            label: '合同金额',
            width: '120px',
            prop: 'contractAmount',
            sortable: false,
            disableCheck: false,
          },
          {
            label: '回款金额',
            width: '120px',
            prop: 'collectedAmount',
            sortable: false,
            disableCheck: false,
          },
          {
            label: '开票金额',
            width: '120px',
            prop: 'invoiceAmount',
            sortable: false,
            disableCheck: false,
          },
          {
            label: '销售工程师',
            width: '120px',
            prop: 'inchargeName',
            sortable: false,
            disableCheck: false,
          },
          {
            label: '审批状态',
            width: '100px',
            prop: 'approStatus',
            sortable: false,
            disableCheck: false,
          },
        ],
      }
    },
    watch: {
      showColumns: function () {
        this.$nextTick(() => this.$refs.table.doLayout())
      },
    },
    activated() {
      this.queryData()
    },
    mounted() {
      this.queryData()
      this.getOptions()
    },
    methods: {
      getOptions() {
        Promise.all([api.getProvinceDetail(), this.getDicts('contract_type'), this.getDicts('sys_product_line')])
          .then(([province, contract, productLine]) => {
            this.contractOptions = {}
            contract.data.values.filter((i) => {
              this.contractOptions[i.key] = i.value
            })
            this.productLineOptions = {}
            productLine.data.values.filter((i) => {
              this.productLineOptions[i.key] = i.value
            })
            this.provinceOptions = province.data.list || []
          })
          .catch((err) => console.log(err))
      },
      async queryData() {
        this.listLoading = true
        const params = { ...this.queryForm }
        params.custProvinceId = params.custProvince ? params.custProvince.id : 0
        params.custCityId = params.custCity ? params.custCity.id : 0
        if (this.queryForm.filterDate && this.queryForm.filterDate.length === 2) {
          params.contractSignTimeStart = this.queryForm.filterDate[0]
          params.contractSignTimeEnd = this.queryForm.filterDate[1]
        }
        const [err, res] = await to(contractApi.getList(params))
        if (err) return (this.listLoading = false)
        this.list = res.data.list || []
        this.total = res.data.total
        this.listLoading = false
        this.$nextTick(() => this.$refs.table.doLayout())
      },
      handleApply(id) {
        this.$refs.applyContract.form.id = id
        this.$refs.applyContract.visible = true
      },
      reset() {
        this.queryForm = {
          pageNum: 1,
          pageSize: 10,
          custCode: '', // 客户编码
          custName: '', //客户名称
          custIndustry: '', // 客户行业  ()
          custLevel: '', //客户级别
        }
        this.queryData()
      },
      handleSizeChange(val) {
        this.queryForm.pageSize = val
        this.queryData()
      },
      handleCurrentChange(val) {
        this.queryForm.pageNum = val
        this.queryData()
      },
      setSelectRows(val) {
        this.selectRows = val.map((item) => item.id)
      },
      // 客户编辑
      async handleEdit(row = null) {
        row ? this.$refs.edit.init(row.id) : this.$refs.edit.init()
      },
      // 合同详情
      handleContractDetail(row) {
        this.$router.push({
          path: '/contract/detail',
          query: {
            id: row.id,
          },
        })
      },
      // 客户详情
      handleCustDetail(row) {
        this.$router.push({
          path: '/customer/detail',
          query: {
            id: row.custId,
          },
        })
      },
      // 转移合同
      handleTransfer(row) {
        this.contractId = row ? [row.id] : this.selectRows
        if (!this.contractId[0]) return this.$baseMessage('请先选择转移的数据', 'warning')
        this.$refs.transfer.open()
      },
      // 合同删除
      handleDelete(row = null) {
        let ids = row ? [row.id] : this.selectRows
        if (!ids[0]) return this.$baseMessage('请先选择删除的数据', 'warning')
        this.$confirm('确认删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(async () => {
            const [err, res] = await to(contractApi.delContract({ id: ids }))
            if (err) return
            if (res.code == 200) {
              this.$message({
                type: 'success',
                message: '删除成功!',
              })
              this.queryData()
            }
          })
          .catch(() => {})
      },
      contractSave() {
        this.queryData()
      },
    },
  }
</script>

<style lang="scss" scoped>
  $base: '.contract-container';
</style>
