<template>
  <div class="user-management-container">
    <div class="side-layout">
      <div class="tree-side">
        <div class="head-container">
          <el-row style="padding-right: 10px" type="flex">
            <el-col><span style="font-size: 25px">公司</span></el-col>
            <el-button type="text" @click="addCompany()">新增</el-button>
          </el-row>
        </div>
        <el-tree
          ref="tree"
          class="filter-tree"
          :data="companyList"
          default-expand-all
          :default-expanded-keys="[1]"
          highlight-current
          node-key="id"
          :props="defaultProps"
          @node-click="handleNodeClick">
          <span slot-scope="{ node }" class="custom-tree-node">
            <span>
              <span>{{ node.label }}</span>
            </span>
            <span>
              <!-- <el-button icon="el-icon-more" type="text" /> -->
              <el-dropdown @command="(command) => treeHandle(command, node)">
                <span class="el-dropdown-link">
                  <i class="el-icon-more"></i>
                  <!-- <i class="el-icon-arrow-down el-icon--right"></i> -->
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-permissions="['partner/company/edit']" command="edit">编辑</el-dropdown-item>
                  <el-dropdown-item v-permissions="['partner/company/del']" command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </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.name"
                  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>
            <el-button icon="el-icon-plus" type="primary" @click="$refs.edit.open(queryForm.partnerId)">添加</el-button>
            <el-button
              v-permissions="['partner/contact/import']"
              icon="el-icon-download"
              type="primary"
              @click="downloadTemplate">
              下载模板
            </el-button>
            <el-upload
              ref="uploadRef"
              action="#"
              :before-upload="
                (file) => {
                  return beforeAvatarUpload(file)
                }
              "
              :file-list="fileList"
              :http-request="uploadrequest"
              :show-file-list="false"
              style="margin: 0 10px 10px 0 !important">
              <el-button v-permissions="['partner/contact/import']" icon="el-icon-upload2" type="primary">
                导入
              </el-button>
            </el-upload>
          </vab-query-form-left-panel>
          <vab-query-form-right-panel>
            <table-tool :columns="columns" :show-columns.sync="showColumns" table-type="partnerTable" />
          </vab-query-form-right-panel>
        </vab-query-form>

        <el-table ref="table" v-loading="listLoading" border :data="list" :height="$baseTableHeight(2)">
          <el-table-column align="center" label="序号" show-overflow-tooltip width="80">
            <template #default="{ $index }">
              {{ $index + 1 }}
            </template>
          </el-table-column>
          <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 }">
              <span>{{ row[item.prop] }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" fixed="right" label="操作" show-overflow-tooltip width="120">
            <template #default="{ row }">
              <el-button v-permissions="['partner/contact/edit']" type="text" @click="$refs.edit.open(row)">
                编辑
              </el-button>
              <el-button type="text" @click="handleDetail(row)">详情</el-button>
              <el-button v-permissions="['partner/contact/del']" 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>
    <partner-edit ref="edit" @fetch-data="fetchData" />
  </div>
</template>

<script>
  import partnerApi from '@/api/base/partner'
  import TableTool from '@/components/table/TableTool'
  import PartnerEdit from './components/PartnerEdit'
  import downloadFileByByte from '@/utils/base64ToFile'
  import to from 'await-to-js'
  import axios from 'axios'
  import asyncUploadFile from '@/utils/uploadajax'
  export default {
    name: 'Product',
    components: { TableTool, PartnerEdit },
    data() {
      return {
        list: [],
        listLoading: false,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        queryForm: {
          pageNum: 1,
          pageSize: 10,
          name: '',
          partnerId: null,
        },
        showColumns: [],
        columns: [
          {
            label: '负责区域',
            width: '220px',
            prop: 'territory',
            sortable: false,
            disableCheck: true,
          },
          {
            label: '联系人',
            prop: 'name',
            width: '120px',
            sortable: false,
            disableCheck: true,
          },
          {
            label: '联系方式',
            width: '120px',
            prop: 'contactWay',
            sortable: false,
          },

          {
            label: '岗位',
            width: '120px',
            prop: 'post',
            sortable: false,
          },
          {
            label: '备注',
            width: 'auto',
            prop: 'remark',
            minWidth: '220px',
            sortable: false,
          },
        ],
        defaultProps: {
          key: 'id',
          label: 'partnerName',
        },
        fileList: [],
        fileSettings: {
          // 文件配置信息
          fileSize: 52428800,
          fileTypes: '.pdf,.doc,.docx,.zip,.xls,.xlsx,.rar,.jpg,.jpeg,.gif,.png,.jfif,.txt',
          pictureSize: 52428800,
          pictureTypes: '.jpg,.jpeg,.gif,.png,.jfif,.txt',
          types: '.pdf,.doc,.docx,.zip,.xls,.xlsx,.rar,.jpg,.jpeg,.gif,.png,.jfif,.mp4,.txt',
          videoSize: 104857600,
          videoType: '.mp4',
        },
        companyList: [], //产品分类
      }
    },
    watch: {
      showColumns: function () {
        this.$nextTick(() => this.$refs.table.doLayout())
      },
    },
    created() {
      this.getCompanyList()
    },
    methods: {
      async treeHandle(command, node) {
        if (command == 'edit') {
          this.addCompany(node)
        } else if (command == 'del') {
          this.$confirm(`确认删除销售区域 ${node.label}?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(async () => {
              const [err, res] = await to(partnerApi.deleteCompany({ id: [node.data.id] }))
              if (err) return
              if (res.code == 200) {
                this.$baseMessage(res.msg, 'success', 'vab-hey-message-success')
                this.getCompanyList()
              }
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消删除',
              })
            })
        }
      },
      async getCompanyList() {
        const [err, res] = await to(partnerApi.getCompanyList({}))
        if (err) return
        if (res.code == 200) {
          this.companyList = res.data.list || []
          if (res.data.list.length > 0) {
            //默认第一选中
            this.$nextTick(() => {
              this.$refs.tree.setCurrentKey(res.data.list[0].id)
              this.queryForm.partnerId = res.data.list[0].id
              this.fetchData()
            })
          }
        }
      },
      async fetchData() {
        console.log(1111111)
        this.listLoading = true
        const [err, res] = await to(partnerApi.getCompanyConcatList(this.queryForm))
        this.listLoading = false
        console.log(this.listLoading)
        if (err) return
        if (res.code == 200) {
          this.total = res.data.total
          this.list = res.data.list || []
        }
      },

      addCompany(node) {
        console.log(node)
        let defVal = ''
        if (node) {
          defVal = node.label
        }
        this.$prompt('请输入公司名称', '提示', {
          inputValue: defVal, // 设置默认值
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /\S+/,
          inputErrorMessage: '公司名称不能为空',
        })
          .then(async ({ value }) => {
            if (node) {
              const params = {
                id: node.data.id,
                partnerName: value,
              }
              const [err, res] = await to(partnerApi.updateCompany(params))
              if (err) return
              if (res.code == 200) {
                this.$baseMessage(res.msg, 'success', 'vab-hey-message-success')
                this.getCompanyList()
              }
            } else {
              const [err, res] = await to(partnerApi.addCompany({ partnerName: value }))
              if (err) return
              if (res.code == 200) {
                this.$baseMessage(res.msg, 'success', 'vab-hey-message-success')
                this.getCompanyList()
              }
            }
            // 当用户点击确定按钮时，执行的逻辑
          })
          .catch(() => {
            // 当用户点击取消按钮时，执行的逻辑
            console.log('取消输入')
          })
      },
      // 节点单击事件
      handleNodeClick(data) {
        console.log(data)
        this.queryForm.partnerId = data.id
        this.fetchData()
      },
      reset() {
        this.queryForm = {
          pageNum: 1,
          pageSize: 10,
          partnerId: null,
          name: '',
        }
        this.fetchData()
      },

      //详情
      handleDetail(row) {
        this.$router.push({
          name: 'PartnersDetail',
          query: {
            id: row.id,
          },
        })
      },

      handleDelete(row) {
        this.$baseConfirm('你确定要删除当前项吗', null, async () => {
          const { msg } = await partnerApi.deleteCompanyConcat({ id: [row.id] })
          this.$baseMessage(msg, 'success', 'vab-hey-message-success')
          await this.fetchData()
        })
      },
      handleSizeChange(val) {
        this.queryForm.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.queryForm.pageNum = val
        this.fetchData()
      },
      queryData() {
        this.queryForm.pageNum = 1
        this.fetchData()
      },
      downloadTemplate() {
        partnerApi
          .downloadFile({})
          .then((res) => {
            if (res.code == 200) {
              downloadFileByByte(res.data, '合作伙伴导入模板.xlsx')
            }
          })
          .catch((err) => {
            console.error(err)
          })
      },

      // 上传图片
      beforeAvatarUpload(file) {
        let flag1 = file.size < this.fileSettings.fileSize
        if (!flag1) {
          this.$message.warning('文件过大，请重新选择！')
          return false
        }
        let flag2 = this.fileSettings.fileTypes.split(',').includes('.' + file.name.split('.').pop())
        if (!flag2) {
          this.$message.warning('文件类型不符合，请重新选择！')
          return false
        }
        return true
      },
      // 上传
      uploadrequest(option) {
        let _this = this
        let url = process.env.VUE_APP_UPLOAD_WEED
        axios
          .post(url)
          .then((res) => {
            if (res.data && res.data.fid && res.data.fid !== '') {
              option.action = `${process.env.VUE_APP_PROTOCOL}${res.data.publicUrl}/${res.data.fid}`
              // let file_name = option.file.name
              // let index = file_name.lastIndexOf('.')
              // let file_extend = ''
              // if (index > 0) {
              //   // 截取名称中的扩展名
              //   file_extend = file_name.substr(index + 1)
              // }
              // let uploadform = {
              //   fileName: file_name, // 资料名称
              //
              //   size: option.file.size.toString(), // 资料大小
              //   fileType: file_extend, // 资料文件类型
              // }
              let fileUrl = `${process.env.VUE_APP_PROTOCOL}${res.data.publicUrl}/${res.data.fid}` // 资料存储url
              asyncUploadFile(option).then(async () => {
                const params = {
                  excelUrl: fileUrl,
                  partnerId: this.queryForm.partnerId,
                }
                const [err, res] = await to(partnerApi.exportFile(params))
                if (err) return
                if (res.code == 200) {
                  _this.$message({
                    type: 'success',
                    message: '上传成功',
                  })
                  this.fetchData()
                }
              })
            } else {
              _this.$message({
                type: 'warning',
                message: '未上传成功！请刷新界面重新上传！',
              })
            }
          })
          .catch(function () {
            _this.$message({
              type: 'warning',
              message: '未上传成功！请重新上传！',
            })
          })
      },
    },
  }
</script>
<style>
  .el-form-item--small {
    margin: 0 0 10px 0 !important;
  }
</style>
