<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.distCode"
                  clearable
                  placeholder="经销商编码"
                  @keyup.enter.native="queryData" />
              </el-form-item> -->
              <el-form-item>
                <el-input
                  v-model.trim="queryForm.distName"
                  clearable
                  placeholder="经销商名称"
                  @keyup.enter.native="queryData" />
              </el-form-item>
              <el-form-item>
                <el-input
                  v-model.trim="queryForm.belongSale"
                  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>

        <vab-query-form-left-panel>
          <el-button v-permissions="['base:agent:add']" icon="el-icon-plus" type="primary" @click="handleEdit($event)">
            新建
          </el-button>
        </vab-query-form-left-panel>
        <vab-query-form-right-panel>
          <table-tool :columns="columns" :show-columns.sync="showColumns" table-type="agentTable" />
        </vab-query-form-right-panel>
        <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 === 'distName'"
                class="link-button"
                style="font-size: 14px"
                type="text"
                @click="handleDetail(row)">
                {{ row.distName }}
              </el-button>
              <span v-else-if="item.prop === 'allProductAmount'">
                {{ formatPrice(row.allProductAmount) }}
              </span>
              <span v-else-if="item.prop === 'saledAmount'">
                {{ formatPrice(row.saledAmount) }}
              </span>
              <span v-else-if="item.prop === 'unpaidAmount'">
                {{ formatPrice(row.unpaidAmount) }}
              </span>
              <span v-else-if="item.prop === 'invoicedAmount'">
                {{ formatPrice(row.invoicedAmount) }}
              </span>
              <span v-else-if="item.prop === 'approItem'">
                {{ row.approStatus == '20' ? row.approItem : '-' }}
              </span>
              <span v-else-if="item.prop === 'approStatus'">
                {{ row.approStatus == '20' ? '待审核' : '-' }}
              </span>
              <span v-else>{{ row[item.prop] }}</span>
            </template>
          </el-table-column>

          <el-table-column align="center" fixed="right" label="操作" show-overflow-tooltip width="180">
            <template #default="{ row }">
              <el-button type="text" @click="changeDistr(row)">转为经销</el-button>
              <el-button type="text" @click="$refs.changeAgent.open(row, 'renewal')">续签</el-button>
              <el-button v-permissions="['base:agent:edit']" type="text" @click="handleEdit(row)">编辑</el-button>
              <el-button v-permissions="['base:agent:delete']" type="text" @click="handleDelete(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>
    <edit ref="edit" @fetch-data="fetchData" />
    <change-agent ref="changeAgent" @fetch-data="fetchData" />
  </div>
</template>

<script>
  import to from 'await-to-js'
  import distrApi from '@/api/base/distr'
  import regionApi from '@/api/base/region'
  import regionAuthApi from '@/api/base/regionAuth'
  import Edit from './components/AgentEdit'
  import TableTool from '@/components/table/TableTool'
  import ChangeAgent from '@/views/base/distributor/components/ChangeAgent'

  export default {
    name: 'Distributor',
    components: { Edit, TableTool, ChangeAgent },
    data() {
      return {
        tableKey: 0,
        list: [],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        selectRows: '',
        queryForm: {
          distType: '20', // 10 经销商 20 代理商
          pageNum: 1,
          pageSize: 10,
          userName: '',
        },
        showColumns: [],
        columns: [
          {
            label: '代理商名称',
            width: '220px',
            prop: 'distName',
            sortable: false,
            disableCheck: true,
          },
          {
            label: '所在省份',
            width: '100px',
            prop: 'provinceDesc',
            sortable: false,
          },
          {
            label: 'ABC项目总数量',
            width: '140px',
            prop: 'projectNum',
            sortable: false,
          },
          {
            label: 'ABC项目出货总金额',
            width: '150px',
            prop: 'allProductAmount',
            sortable: false,
          },
          {
            label: '成交项目数量',
            width: '140px',
            prop: 'saledProjectNum',
            sortable: false,
          },
          {
            label: '成交总金额',
            width: '100px',
            prop: 'saledAmount',
            sortable: false,
          },
          {
            label: '未回款总金额',
            width: '140px',
            prop: 'unpaidAmount',
            sortable: false,
          },
          {
            label: '开票总金额',
            width: '100px',
            prop: 'invoicedAmount',
            sortable: false,
          },
          {
            label: '归属销售',
            width: 'auto',
            prop: 'belongSale',
            sortable: false,
          },
          {
            label: '业务范围',
            width: 'auto',
            prop: 'businessScope',
            sortable: false,
          },
          {
            label: '审核类型',
            width: 'auto',
            prop: 'approItem',
            sortable: false,
          },
          {
            label: '审核状态',
            width: 'auto',
            prop: 'approStatus',
            sortable: false,
          },
          {
            label: '创建时间',
            width: '100px',
            prop: 'createdTime',
            sortable: false,
          },
        ],

        regionOptions: [],
        userSalesProvince: undefined,
        defaultProps: {
          id: 'id',
          children: 'children',
          label: 'regionDesc',
        },
        treeDefaultExpandAll: true,
      }
    },
    watch: {
      showColumns: function () {
        this.tableKey++
        this.$nextTick(() => this.$refs.table.doLayout())
      },
    },
    activated() {
      this.fetchData()
    },
    created() {
      this.fetchData()
      this.getRegionTree()
      this.getUserSalesProvince()
    },
    methods: {
      // 转经销商
      changeDistr(row) {
        console.log(row)
        this.$prompt('请输入转经销商原因', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /\S+/,
          inputErrorMessage: '原因不能为空',
        })
          .then(async ({ value }) => {
            // 当用户点击确定按钮时，执行的逻辑
            console.log('输入的值为:', value)
            const [err, res] = await to(distrApi.changeDistr({ id: row.id, customerType: value }))
            if (err) return
            if (res.code == 200) {
              this.$baseMessage('转经销商成功', 'success', 'vab-hey-message-success')
              this.handleCurrentChange(1)
            }
          })
          .catch(() => {
            // 当用户点击取消按钮时，执行的逻辑
            console.log('取消输入')
          })
      },
      async getRegionTree() {
        const { data: data } = await regionApi.getRegionTree({})
        this.regionOptions.push(...data.list)
      },
      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.provinceId = data.children.map((item) => item.regionCode)
        } else {
          this.queryForm.provinceId = [data.regionCode]
        }
        this.fetchData()
      },
      setSelectRows(val) {
        this.selectRows = val
      },
      handleEdit(row) {
        if (row.id) {
          this.$refs['edit'].showEdit(row)
        } else {
          this.$refs['edit'].showEdit()
        }
      },
      handleDelete(row) {
        if (row.id) {
          this.$baseConfirm('你确定要删除当前项吗', null, async () => {
            const { msg } = await distrApi.doDelete({ 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 distrApi.doDelete({ 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 = Object.assign(this.queryForm, { withStatistic: true, distType: '20' })
        const {
          data: { list, total },
        } = await distrApi.getList(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: '/base/agentDetails',
          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>
