<template>
  <div class="business-container">
    <el-tabs v-model="activeName" @tab-click="handleTabClick">
      <el-tab-pane label="全部项目" name="all" />
      <el-tab-pane label="A类项目" name="10" />
      <el-tab-pane label="B类项目" name="20" />
      <el-tab-pane label="C类项目" name="30" />
      <el-tab-pane label="储备项目" name="50" />
      <el-tab-pane label="成交项目" name="40" />
    </el-tabs>
    <vab-query-form>
      <vab-query-form-top-panel>
        <el-form ref="queryForm" :inline="true" :model="queryForm" @submit.native.prevent>
          <!--          <el-form-item prop="nboName">-->
          <!--            <el-input v-model="queryForm.nboName" clearable placeholder="项目名称" @keyup.enter.native="queryData" />-->
          <!--          </el-form-item>-->

          <el-form-item prop="custName">
            <el-input
              v-model="queryForm.custName"
              clearable
              placeholder="客户名称"
              size="small"
              @keyup.enter.native="queryData" />
          </el-form-item>

          <el-form-item v-show="activeName === 'all'" prop="nboType">
            <el-select v-model="queryForm.nboType" clearable placeholder="项目类别">
              <el-option v-for="dict in nboTypeOptions" :key="dict.key" :label="dict.value" :value="dict.key" />
            </el-select>
          </el-form-item>
          <el-form-item prop="saleName">
            <el-input
              v-model="queryForm.saleName"
              clearable
              placeholder="销售工程师"
              size="small"
              @keyup.enter.native="queryData" />
          </el-form-item>
          <el-form-item prop="productLine">
            <el-select v-model="queryForm.productLine" clearable placeholder="产品线">
              <el-option v-for="item in productLineOptions" :key="item.key" :label="item.value" :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item prop="nboSource">
            <el-select v-model="queryForm.nboSource" clearable placeholder="项目来源">
              <el-option v-for="dict in nboSourceOptions" :key="dict.key" :label="dict.value" :value="dict.key" />
            </el-select>
          </el-form-item>
          <el-form-item prop="distributorName">
            <el-input
              v-model="queryForm.distributorName"
              clearable
              placeholder="经销商/代理商"
              size="small"
              @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="filingTime">
            <el-date-picker
              v-model="queryForm.filingTime"
              end-placeholder="结束"
              start-placeholder="备案日期开始"
              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-button icon="el-icon-refresh" type="primary" @click="resetQuery">重置</el-button>
            <el-button v-permissions="['proj:business:add']" icon="el-icon-plus" type="primary" @click="handleEdit({})">
              新增项目
            </el-button>
            <el-button
              v-permissions="['proj:business:transfer']"
              icon="el-icon-refresh"
              type="primary"
              @click="handleTransfer">
              转移项目
            </el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-top-panel>

      <vab-query-form-left-panel :span="12">
        <!--        <el-button icon="el-icon-plus" type="primary" @click="handleEdit">创建任务</el-button>-->
        <!--        <el-button icon="el-icon-plus" type="primary" @click="handleEdit">创建工单</el-button>-->
        <!--        <el-button icon="el-icon-plus" type="primary" @click="handleEdit">创建合同</el-button>-->
        <!--        <el-button icon="el-icon-delete" type="danger" @click="handleDelete">删除</el-button>-->
      </vab-query-form-left-panel>
      <vab-query-form-right-panel :span="12">
        <table-tool
          ref="tableTool"
          :columns.sync="finallyColumns"
          :show-columns.sync="showColumns"
          :table-type.sync="tableType" />
      </vab-query-form-right-panel>
    </vab-query-form>

    <el-table
      :key="tableKey"
      ref="busTable"
      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.minWidth"
        :prop="item.prop"
        show-overflow-tooltip
        :sortable="item.sortable"
        :width="item.width">
        <template #default="{ row }">
          <el-button
            v-if="item.prop === 'nboCode' || item.prop === 'nboName'"
            class="link-button"
            type="text"
            @click="handleDetail(row)">
            {{ row[item.prop] }}
          </el-button>
          <span v-else-if="item.prop === 'nboType'">
            {{ selectDictLabel(nboTypeOptions, row.nboType) }}
          </span>
          <span v-else-if="item.prop === 'nboSource'">
            {{ selectDictLabel(nboSourceOptions, row.nboSource) }}
          </span>
          <span v-else-if="item.prop === 'salesModel'">
            {{ selectDictLabel(salesModelOptions, row.salesModel) }}
          </span>
          <span v-else-if="item.prop === 'approStatus'">
            {{ selectDictLabel(approStatusOptions, row.approStatus) }}
          </span>
          <span v-else-if="item.prop === 'nboStatus'">
            {{ selectDictLabel(nboStatusOptions, row.nboStatus) }}
          </span>
          <span v-else-if="item.prop === 'nboPhase'">
            {{ selectDictLabel(nboPhaseOptions, row.nboPhase) }}
          </span>
          <span v-else-if="item.prop === 'productLine'">
            {{ selectDictLabel(productLineOptions, row.productLine) }}
          </span>
          <span v-else-if="item.prop === 'isBig'">
            {{ selectDictLabel(yesOrNoOptions, row.isBig) }}
          </span>
          <span v-else-if="item.prop === 'estTransPrice'">
            {{ formatPrice(row.estTransPrice) }}
          </span>
          <span v-else-if="item.prop === 'nboBudget'">
            {{ formatPrice(row.nboBudget) }}
          </span>
          <span v-else-if="item.prop === 'contractAmount'">
            {{ formatPrice(row.contractAmount) }}
          </span>
          <span v-else-if="item.prop === 'filingTime'">
            {{ parseTime(row.filingTime, '{y}-{m}-{d}') }}
          </span>
          <span v-else-if="item.prop === 'finalFollowTime'">
            {{ parseTime(row.finalFollowTime, '{y}-{m}-{d}') }}
          </span>
          <span v-else-if="item.prop === 'nextFollowTime'">
            {{ parseTime(row.nextFollowTime, '{y}-{m}-{d}') }}
          </span>
          <span v-else-if="item.prop === 'projClosingTime'">
            {{ parseTime(row.projClosingTime, '{y}-{m}-{d}') }}
          </span>
          <span v-else-if="item.prop === 'projConversionTime'">
            {{ parseTime(row.projConversionTime, '{y}-{m}-{d}') }}
          </span>
          <span v-else>{{ row[item.prop] }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" fixed="right" label="操作" width="68">
        <template #default="{ row }">
          <!--          <el-button type="text" @click="handleFollow(row)">跟进</el-button>-->
          <el-button v-permissions="['proj:business:edit']" type="text" @click="handleEdit(row)">编辑</el-button>
          <!--                    <el-button type="text" @click="handleDelete(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" />
    <!-- 添加 -->
    <add ref="add" @fetch-data="fetchData" />
    <!-- 编辑 -->
    <edit ref="edit" @fetch-data="fetchData" />
    <!-- 转移 -->
    <transfer ref="transfer" @fetch-data="fetchData" />
    <!-- 添加跟进记录 -->
    <follow-add ref="follow" @fetch-data="fetchData" />
  </div>
</template>

<script>
  import businessApi from '@/api/proj/business'
  import Edit from './components/BusinessEdit'
  import Add from './components/BusinessAdd'
  import Transfer from './components/Transfer'
  import FollowAdd from './components/FollowAdd'
  import TableTool from '@/components/table/TableTool'
  import customerApi from '@/api/customer'

  export default {
    name: 'Business',
    components: { Edit, Transfer, TableTool, FollowAdd, Add },
    data() {
      return {
        tableKey: 0,
        activeName: '',
        height: this.$baseTableHeight(4),
        queryForm: {
          pageNum: 1,
          pageSize: 10,
          nboName: undefined,
          custName: undefined,
          nboType: undefined,
          saleName: undefined,
          productLine: undefined,
          nboSource: undefined,
          distributorName: undefined,
          custProvince: null,
          filingTime: undefined,
          beginTime: undefined,
          endTime: undefined,
        },
        tableType: 'businessTable',
        showColumns: [],
        columns: [
          {
            label: '项目编码',
            prop: 'nboCode',
            width: '120px',
            minWidth: '120px',
            sortable: false,
            disableCheck: true,
          },
          {
            label: '项目名称',
            prop: 'nboName',
            width: '240px',
            minWidth: '240px',
            sortable: false,
            disableCheck: true,
          },
          {
            label: '所在省',
            prop: 'custProvince',
            width: '100px',
          },
          {
            label: '所在市',
            prop: 'custCity',
            width: '100px',
          },
          {
            label: '销售工程师',
            prop: 'saleName',
            width: '100px',
          },
          {
            label: '客户名称',
            prop: 'custName',
            width: 'auto',
            minWidth: '240px',
          },
          {
            label: '项目备案时间',
            prop: 'filingTime',
            width: '110px',
          },
          {
            label: '项目来源',
            prop: 'nboSource',
            width: '140px',
          },
          {
            label: '销售模式',
            prop: 'salesModel',
            width: '80px',
          },
          {
            label: '经销商/代理商',
            prop: 'distributorName',
            minWidth: '240px',
            width: 'auto',
          },
          {
            label: '产品线',
            prop: 'productLine',
            width: '140px',
          },
          {
            label: '项目类别',
            prop: 'nboType',
            width: '80px',
          },
          {
            label: '项目预算',
            prop: 'nboBudget',
            width: '120px',
          },
          {
            label: '出货金额',
            prop: 'estTransPrice',
            width: '120px',
          },
          {
            label: '大项目',
            prop: 'isBig',
            width: '70px',
          },
          {
            label: '最新跟进时间',
            prop: 'finalFollowTime',
            width: '110px',
          },
          {
            label: '最新跟进人',
            prop: 'finalFollowName',
            width: '50px',
          },
          {
            label: '项目成交时间',
            prop: 'projClosingTime',
            width: '110px',
          },
          {
            label: '合同金额',
            prop: 'contractAmount',
            width: '140px',
          },
          {
            label: '项目转化时间',
            prop: 'projConversionTime',
            width: '110px',
          },
          {
            label: '转化原因',
            prop: 'projConversionReason',
            width: '140px',
          },
        ],
        allColumns: [
          '项目编码',
          '项目名称',
          '销售工程师',
          '所在省',
          '所在市',
          '客户名称',
          '项目备案时间',
          '项目来源',
          '销售模式',
          '经销商/代理商',
          '产品线',
          '项目类别',
          '项目预算',
          '出货金额',
          '大项目',
          '最新跟进时间',
        ],
        abcColumns: [
          '项目编码',
          '项目名称',
          '所在省',
          '所在市',
          '销售工程师',
          '客户名称',
          '项目备案时间',
          '项目来源',
          '销售模式',
          '经销商/代理商',
          '产品线',
          '项目预算',
          '出货金额',
          '大项目',
          '最新跟进时间',
          '最新跟进',
        ],
        dealColumns: [
          '项目编码',
          '项目名称',
          '所在省',
          '所在市',
          '销售工程师',
          '客户名称',
          '项目备案时间',
          '项目来源',
          '销售模式',
          '经销商/代理商',
          '产品线',
          '大项目',
          '项目成交时间',
          '合同金额',
        ],
        reserveColumns: [
          '项目编码',
          '项目名称',
          '所在省',
          '所在市',
          '销售工程师',
          '客户名称',
          '项目备案时间',
          '项目来源',
          '销售模式',
          '经销商/代理商',
          '产品线',
          '项目转化时间',
          '转化原因',
        ],
        list: [],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        selectRows: '',
        yesOrNoOptions: [],
        nboTypeOptions: [],
        nboSourceOptions: [],
        salesModelOptions: [],
        productLineOptions: [],
        nboPhaseOptions: [],
        nboStatusOptions: [],
        approStatusOptions: [],
        followup: {},
        finallyColumns: [],
        provinceOptions: [],
      }
    },
    watch: {
      showColumns: function () {
        this.tableKey++
        this.$nextTick(() => this.$refs.busTable.doLayout())
      },
      activeName(newValue) {
        this.tableType = 'businessTable' + this.selectDictLabel(this.nboTypeOptions, newValue)
        switch (newValue) {
          case '10':
          case '20':
          case '30':
            this.finallyColumns = this.columns.filter((item) => this.abcColumns.includes(item.label))
            break
          case '40':
            this.finallyColumns = this.columns.filter((item) => this.dealColumns.includes(item.label))
            break
          case '50':
            this.finallyColumns = this.columns.filter((item) => this.reserveColumns.includes(item.label))
            break
          default:
            this.finallyColumns = this.columns.filter((item) => this.allColumns.includes(item.label))
        }
      },
    },
    activated() {
      this.fetchData()
    },
    created() {
      this.activeName = 'all'
      if (this.$route.params && this.$route.params.length > 0) {
        this.queryForm = this.$route.params
        this.activeName = this.queryForm.activeName ? this.queryForm.activeName : 'all'
      }
      this.handleTabClick()
      this.getOptions()
    },
    updated() {
      if (this.$refs.busTable && this.$refs.busTable.doLayout) {
        this.$refs.busTable.doLayout()
      }
    },
    methods: {
      getOptions() {
        Promise.all([
          this.getDicts('proj_nbo_type'),
          this.getDicts('proj_nbo_source'),
          this.getDicts('proj_sales_model'),
          this.getDicts('sys_product_line'),
          this.getDicts('sys_yes_no'),
          // this.getDicts('proj_nbo_phase'),
          // this.getDicts('proj_nbo_status'),
          // this.getDicts('proj_appro_status'),
          customerApi.getProvinceDetail(),
        ])
          .then(([nboType, nboSource, salesModel, productLine, yesOrNo, province]) => {
            this.nboTypeOptions = nboType.data.values || []
            this.nboSourceOptions = nboSource.data.values || []
            this.salesModelOptions = salesModel.data.values || []
            this.productLineOptions = productLine.data.values || []
            this.yesOrNoOptions = yesOrNo.data.values || []
            // this.nboPhaseOptions = nboPhase.data.values || []
            // this.nboStatusOptions = nboStatus.data.values || []
            // this.approStatusOptions = approStatus.data.values || []
            this.provinceOptions = province.data.list || []
          })
          .catch((err) => console.log(err))
      },
      handleTabClick() {
        this.queryForm.pageNum = 1
        if (this.activeName !== 'all') {
          this.queryForm.nboType = this.activeName
        } else {
          this.queryForm.nboType = undefined
        }
        this.$nextTick(() => {
          this.$refs['tableTool'].getInitData()
        })
        this.fetchData()
      },
      handleTransfer() {
        if (this.selectRows.length !== 1) {
          this.$baseMessage('请选择一个项目', 'warning')
          return
        }
        this.$refs['transfer'].open(this.selectRows[0])
      },
      // 跳转详情
      handleDetail(row) {
        this.queryForm.activeName = this.activeName
        this.$router.push({
          name: 'BusinessDetail',
          query: {
            id: row.id,
          },
          params: this.queryForm,
        })
      },
      handleFollow(row) {
        this.followup = {
          targetId: row.id,
          targetType: '20',
          targetName: row.nboName,
          custId: row.custId,
          custName: row.custName,
          contactsId: row.contactId,
          contactsName: row.contactName,
        }
        console.log(this.followup)
        this.$refs.follow.showEdit(this.followup)
      },
      handleEdit(row) {
        if (row.id) {
          this.$refs['add'].showEdit(row)
        } else {
          this.$refs['add'].showEdit(row)
        }
      },
      handleDelete(row) {
        if (row.id) {
          this.$baseConfirm('你确定要删除当前项吗', null, async () => {
            const { msg } = await businessApi.doDelete({ ids: [row.id] })
            this.$baseMessage(msg, 'success')
            await this.fetchData()
          })
        } else {
          if (this.selectRows.length > 0) {
            const ids = this.selectRows.map((item) => item.id)
            this.$baseConfirm('你确定要删除选中项吗', null, async () => {
              const { msg } = await businessApi.doDelete({ ids })
              this.$baseMessage(msg, 'success')
              await this.fetchData()
            })
          } else {
            this.$baseMessage('未选中任何行', 'error')
            return false
          }
        }
      },
      handleSizeChange(val) {
        this.queryForm.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.queryForm.pageNum = val
        this.fetchData()
      },
      queryData() {
        this.queryForm.pageNum = 1
        this.fetchData()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm('queryForm')
        this.handleTabClick()
      },
      setSelectRows(val) {
        this.selectRows = val
      },
      async fetchData() {
        if (this.queryForm.filingTime && this.queryForm.filingTime.length === 2) {
          this.queryForm.beginTime = this.queryForm.filingTime[0] + ' 00:00:00'
          this.queryForm.endTime = this.queryForm.filingTime[1] + ' 23:59:59'
        } else {
          this.queryForm.beginTime = undefined
          this.queryForm.endTime = undefined
        }
        this.listLoading = true
        this.queryForm.provinceId = this.queryForm.custProvince.id
        const { data } = await businessApi.getList(this.queryForm)
        const { list, total } = data
        this.list = list
        this.total = total
        this.listLoading = false
        this.tableKey++
        this.$nextTick(() => this.$refs.busTable.doLayout())
      },
    },
  }
</script>
