<template>
  <div class="user-management-container">
    <div class="side-layout">
      <div class="tree-side">
        <span style="font-size: 25px">招标区域</span>
        <el-tree
          ref="tree"
          :data="regionOptions"
          default-expand
          :default-expand-all="false"
          :expand-on-click-node="true"
          :filter-node-method="filterNode"
          highlight-current
          node-key="id"
          :props="defaultProps"
          @node-click="handleNodeClick">
          <span slot-scope="{ node }" class="custom-tree-node">
            <span>{{ node.label }}</span>
            <span>
              <i class="el-icon-more"></i>
            </span>
          </span>
        </el-tree>
      </div>
      <div class="tree-table">
        <vab-query-form>
          <vab-query-form-top-panel>
            <el-form :inline="true" :model="queryForm" @submit.native.prevent>
              <el-form-item>
                <el-input
                  v-model.trim="queryForm.productName"
                  clearable
                  placeholder="产品名称"
                  @keyup.enter.native="queryData" />
              </el-form-item>
              <el-form-item>
                <el-input
                  v-model.trim="queryForm.title"
                  clearable
                  placeholder="招标信息标题"
                  @keyup.enter.native="queryData" />
              </el-form-item>
              <el-form-item>
                <el-input
                  v-model.trim="queryForm.bidder"
                  clearable
                  placeholder="中标单位"
                  @keyup.enter.native="queryData" />
              </el-form-item>
              <el-form-item>
                <el-button icon="el-icon-search" type="primary" @click="queryData">查询</el-button>
                <el-button icon="el-icon-refresh-right" @click="reset">重置</el-button>
              </el-form-item>
            </el-form>
          </vab-query-form-top-panel>
          <vab-query-form-left-panel :span="12">
            <el-button v-permissions="['base:bid:add']" icon="el-icon-plus" type="primary" @click="addBid">
              新建招标记录
            </el-button>
            <el-button
              v-permissions="['base:distributor:add']"
              icon="el-icon-plus"
              type="primary"
              @click="addDistributor">
              新建经销商
            </el-button>
          </vab-query-form-left-panel>
          <vab-query-form-right-panel :span="12">
            <table-tool :columns="columns" :show-columns.sync="showColumns" table-type="collectionTable" />
          </vab-query-form-right-panel>
        </vab-query-form>
        <el-table
          :key="tableKey"
          ref="table"
          v-loading="listLoading"
          border
          :data="list"
          :height="$baseTableHeight(2)"
          @selection-change="setSelectRows">
          <el-table-column
            v-for="(item, index) in showColumns"
            :key="index"
            align="center"
            :label="item.label"
            :prop="item.prop"
            show-overflow-tooltip
            :sortable="item.sortable"
            :width="item.width">
            <template #default="{ row }">
              <el-button v-if="item.prop === 'title'" style="font-size: 14px" type="text" @click="handleDetail(row)">
                {{ row.title }}
              </el-button>
              <span v-else-if="item.prop === 'infoType'">
                {{ bidInfoTypeOptions[row.infoType] }}
              </span>
              <span v-else-if="item.prop === 'productLine'">
                {{ selectDictLabel(productLineOptions, row.productLine) }}
              </span>
              <span v-else-if="item.prop === 'status'">
                {{ selectDictLabel(bidStatus, row.status) }}
              </span>
              <span v-else>{{ row[item.prop] }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" fixed="right" label="操作" width="180px">
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.status == '10' || scope.row.status == '40'"
                v-permissions="['base:bid:add']"
                type="text"
                @click="bidEdit(scope.row)">
                编辑
              </el-button>
              <el-button
                v-if="scope.row.status == '10' || scope.row.status == '40'"
                v-permissions="['base:bid:delete']"
                type="text"
                @click="bidDel(scope.row)">
                删除
              </el-button>
              <el-button
                v-if="scope.row.status == '10' || scope.row.status == '40'"
                v-permissions="['proj:business:add']"
                type="text"
                @click="addProjBusiness(scope.row)">
                新增项目
              </el-button>
              <el-button
                v-if="scope.row.status == '10' || scope.row.status == '40'"
                type="text"
                @click="closeLoop(scope.row)">
                闭环
              </el-button>
            </template>
          </el-table-column>
          <template #empty>
            <el-image class="vab-data-empty" :src="require('@/assets/empty_images/data_empty.png')" />
          </template>
        </el-table>
        <el-pagination
          background
          :current-page="queryForm.pageNum"
          :layout="layout"
          :page-size="queryForm.pageSize"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange" />
      </div>
    </div>
    <!-- 招标信息 -->
    <Bid ref="bid" @bidSave="fetchData" />
    <!-- 项目 -->
    <addBusiness ref="addBusiness" />
    <!-- 经销商 -->
    <addDistributor ref="addDistributor" />
    <!-- 闭环 -->
    <closeLoopDialog ref="closeLoopDialog" @doRefesh="fetchData" />
  </div>
</template>

<script>
  import bidApi from '@/api/customer/bid'
  import regionApi from '@/api/base/region'
  import regionAuthApi from '@/api/base/regionAuth'
  import TableTool from '@/components/table/TableTool'
  import to from 'await-to-js'
  import Bid from '../components/Bid'
  import addBusiness from '@/views/proj/business/components/BusinessAdd'
  import addDistributor from '@/views/base/distributor/components/DistrEdit'
  import closeLoopDialog from './components/closeLoop'

  export default {
    name: 'Distributor',
    components: { TableTool, Bid, addBusiness, addDistributor, closeLoopDialog },
    data() {
      return {
        tableKey: 0,
        list: [],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        selectRows: '',
        queryForm: {
          pageNum: 1,
          pageSize: 10,
          productName: '',
          title: '',
          bidder: '',
          custProvinceId: null,
        },
        showColumns: [],
        columns: [
          {
            label: '招标信息标题',
            width: '320px',
            prop: 'title',
            sortable: false,
          },
          {
            label: '招标产品名称',
            width: '160px',
            prop: 'productName',
            sortable: false,
          },
          {
            label: '发布日期',
            width: '160px',
            prop: 'publishedTime',
            sortable: false,
          },
          {
            label: '状态',
            width: '150px',
            prop: 'status',
            sortable: false,
          },
          {
            label: '预算',
            width: '100px',
            prop: 'budget',
            sortable: false,
          },
          {
            label: '产品线',
            width: '150px',
            prop: 'productLine',
            sortable: false,
          },
          {
            label: '客户名称',
            width: 'auto',
            prop: 'cuctName',
            sortable: false,
          },
          {
            label: '信息分类',
            width: '100px',
            prop: 'infoType',
            sortable: false,
          },
          {
            label: '中标单位',
            width: '100px',
            prop: 'bidder',
            sortable: false,
          },
          {
            label: '创建招标日期',
            width: '160px',
            prop: 'biddingTime',
            sortable: false,
          },
          {
            label: '闭环信息描述',
            width: 'auto',
            prop: 'closeLoopMsg',
            sortable: false,
          },
          {
            label: '渠道推进工作',
            width: 'auto',
            prop: 'channelPromotionWork',
            sortable: false,
          },
          {
            label: '客户推进工作',
            width: 'auto',
            prop: 'customerPromotionWork',
            sortable: false,
          },
          {
            label: '客户后续销售机会',
            width: 'auto',
            prop: 'customerSubsequentOpportunity',
            sortable: false,
          },
          {
            label: '备注',
            width: 'auto',
            prop: 'remark',
            sortable: false,
            disableCheck: false,
          },
        ],
        regionOptions: [],
        userSalesProvince: undefined,
        defaultProps: {
          id: 'id',
          children: 'children',
          label: 'regionDesc',
        },
        treeDefaultExpandAll: true,
        bidInfoTypeOptions: {},
        productLineOptions: [],
        bidStatus: [],
      }
    },
    watch: {
      showColumns: function () {
        this.tableKey++
        this.$nextTick(() => this.$refs.table.doLayout())
      },
    },
    activated() {
      this.fetchData()
    },
    created() {
      this.getOptions()
      this.fetchData()
      this.getRegionTree()
    },
    methods: {
      // 闭环
      closeLoop(row) {
        this.$refs.closeLoopDialog.init(row)
      },
      // 新建经销商
      addDistributor() {
        this.$refs['addDistributor'].showEdit()
      },
      // 新增项目
      addProjBusiness(row) {
        let bid = JSON.parse(JSON.stringify(row))
        this.$refs['addBusiness'].showEdit({}, bid)
      },
      // 新增
      addBid() {
        this.$refs.bid.init()
      },
      // 编辑
      bidEdit(row) {
        this.$refs.bid.init(row.id)
      },
      // 删除招标信息
      bidDel(row) {
        this.$confirm('确认删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(async () => {
            const [err, res] = await to(bidApi.delete({ id: [row.id] }))
            if (err) return
            if (res.code == 200) {
              this.$message({
                type: 'success',
                message: '删除成功!',
              })
              this.fetchData()
            }
          })
          .catch((err) => {
            console.error(err)
          })
      },
      getOptions() {
        this.getDicts('bid_info_type').then((response) => {
          this.bidInfoTypeOptions = {}
          response.data.values.filter((i) => {
            this.bidInfoTypeOptions[i.key] = i.value
          })
        })
        this.getDicts('sys_product_line').then((response) => {
          this.productLineOptions = response.data.values || []
        })
        this.getDicts('bid_status').then((response) => {
          this.bidStatus = response.data.values || []
        })
      },
      async getRegionTree() {
        const { data: data } = await regionApi.getRegionTree({ isPermission: '1' })
        for (let val of data.list) {
          if (val.regionDesc === '其他区域') {
            val.regionDesc = '负责区域'
            this.regionOptions.unshift(val)
          } else {
            this.regionOptions.push(val)
          }
        }
      },
      async getUserSalesProvince() {
        const { data: data } = await regionAuthApi.getUserSalesProvince({})
        if (data && data.list) {
          this.regionOptions.unshift(data.list)
        }
      },
      // 筛选节点
      filterNode(value, data) {
        if (!value) return true
        return data[this.defaultProps.label].indexOf(value) !== -1
      },
      // 节点单击事件
      handleNodeClick(data) {
        if (data.children && data.children.length) {
          this.queryForm.custProvinceId = data.children.map((item) => item.regionCode)
        } else {
          this.queryForm.custProvinceId = [data.regionCode]
        }
        this.fetchData()
      },
      setSelectRows(val) {
        this.selectRows = val
      },
      handleDelete(row) {
        if (row.id) {
          this.$baseConfirm('你确定要删除当前项吗', null, async () => {
            const { msg } = await bidApi.delete({ ids: [row.id] })
            this.$baseMessage(msg, 'success', 'vab-hey-message-success')
            await this.fetchData()
          })
        } else {
          if (this.selectRows.length > 0) {
            const ids = this.selectRows.map((item) => parseInt(item.id))
            console.log(ids)
            this.$baseConfirm('你确定要删除选中项吗', null, async () => {
              const { msg } = await bidApi.delete({ ids })
              this.$baseMessage(msg, 'success', 'vab-hey-message-success')
              await this.fetchData()
            })
          } else {
            this.$baseMessage('未选中任何行', 'error', 'vab-hey-message-error')
          }
        }
      },
      handleSizeChange(val) {
        this.queryForm.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.queryForm.pageNum = val
        this.fetchData()
      },
      queryData() {
        this.queryForm.pageNum = 1
        this.fetchData()
      },
      async fetchData() {
        this.listLoading = true
        const params = this.queryForm
        const {
          data: { list, total },
        } = await bidApi.list(params)
        this.list = list
        this.total = total
        this.listLoading = false
        this.tableKey++
        this.$nextTick(() => this.$refs.table.doLayout())
      },
      reset() {
        this.queryForm = {
          pageNum: 1,
          pageSize: 10,
          distName: '',
          belongSale: '',
        }
        this.fetchData()
      },
      //详情
      handleDetail(row) {
        this.$router.push({
          path: '/customer/inviteDetail',
          query: {
            id: row.id,
          },
        })
      },
    },
  }
</script>

<style>
  .el-tree-node:focus > .el-tree-node__content {
    /*设置选中的样式 */
    background-color: #dde9ff !important;
  }

  .el-tree-node__content:hover {
    /*设置鼠标飘过的颜色 */
    background: #eaf9ff !important;
    color: #007bff;
  }

  .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
    /*current选中的样式 */
    color: #4d95fd;
    font-weight: bold;
    background-color: #dde9ff !important;
  }
</style>
