<template>
  <div>
    <basic-container v-show="!detailsOpen">
      <el-row>
        <el-col :span="4">
          <avue-tree :option="treeOption" :data="treeData" @node-click="nodeClick" style="height:73vh;"
            @save="corpTypeVisible = true">
            <template slot="addBtn">
              <el-tooltip class="item" effect="dark" content="新建分类" placement="top">
              <i class="el-icon-setting"  style="font-size:18px;line-height: 30px;width: 20px;padding: 0 10px;"
                @click="corpTypeVisible = true"></i>
              </el-tooltip>
            </template>
          </avue-tree>
        </el-col>
        <el-col :span="20">
          <avue-crud :option="option" :search.sync="search" v-model="form" :table-loading="loading" :data="dataList"
            ref="crud" :key="key" @on-load="onLoad" @search-change="searchChange" @row-del="rowDel"
            @refresh-change="refreshChange" @resetColumn="resetColumnTwo('crud', 'option', 'optionList', 262)"
            @saveColumn="saveColumnTwo('crud', 'option', 'optionList', 262)" :page.sync="page">
            <template slot-scope="{type,size,row,index}" slot="menu">
              <!-- <el-button  :size="size" :type="type" @click="check(row)">查看</el-button> -->
              <el-button  :size="size" :type="type" :disabled="row.enableOrNot"
                @click="$refs.crud.rowDel(row, index)">删除</el-button>
            </template>
            <template slot-scope="{ row, index }" slot="cname">
              <span style="color: #409EFF;cursor: pointer" @click.stop="check(row)">{{ row.cname }}</span>
            </template>
            <template slot="enableOrNot" slot-scope="{row,index,disabled}">
<!--              <el-switch active-value="1" inactive-value="0" :disabled="disabled" v-model="row.enableOrNot">-->
<!--              </el-switch>-->
              <div v-if="row.enableOrNot === 1">是</div>
              <div v-else style="color: red">否</div>
            </template>
            <template slot="corpNameSearch">
              <crop-select v-model="search.corpId" corpType="KH" :refresh="false"></crop-select>
            </template>
            <template slot="shippingCompanyNameSearch">
              <crop-select v-model="search.shippingCompanyId" corpType="KH" :refresh="false"></crop-select>
            </template>
            <template slot-scope="scope" slot="bookingAgentSearch">
              <crop-select v-model="search.bookingAgentId" corpType="KH" :refresh="false"></crop-select>
            </template>
            <template slot-scope="{type,size,row,$index}" slot="menuLeft">
              <el-button icon="el-icon-plus" type="primary" :size="size" @click="detailsOpen = true">新增供应商</el-button>
              <el-button type="primary" size="small" icon="el-icon-bottom" @click="excelBox = true">导入</el-button>
            </template>
          </avue-crud>
        </el-col>
      </el-row>
    </basic-container>
    <el-dialog title="导入供应商" append-to-body :visible.sync="excelBox" width="555px" :close-on-click-modal="false"
      v-dialog-drag>
      <avue-form :option="excelOption" v-model="excelForm" table-loading="excelLoading" :upload-before="uploadBefore"
        :upload-after="uploadAfter">
        <template slot="excelTemplate">
          <el-button type="primary" @click="derivation">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
      <p style="text-align: center;color: #DC0505">
        温馨提示 第一次导入时请先下载模板
      </p>
    </el-dialog>
    <el-dialog title="设置供应商分类" v-dialogDrag :visible.sync="corpTypeVisible" class="avue-dialog" width="80%" append-to-body
      @closed="corpTypeClosed">
      <span>
        <corp-type corpType="GYS"></corp-type>
        <!-- <avue-form :key="reload" ref="corpType" v-model="form4" :option="option4" style="margin-top:20px">
        </avue-form> -->
      </span>
      <div class="avue-dialog__footer">
        <el-button @click="corpTypeVisible = false" size="mini">取 消</el-button>
        <el-button @click="addCorpType" type="primary" size="mini">确 定</el-button>
      </div>
    </el-dialog>
    <detailsPage v-if="detailsOpen" :onLoad="form" :detailData="detailData" @backToList="backToList"></detailsPage>
  </div>
</template>

<script>
// import {getList, remove} from "@/api/oceanShipping/maritimeExport/index.js";
import detailsPage from "./detailsPage"
import { getToken } from "@/util/auth";
import { getCorpType, getList, remove } from "@/api/tirePartsMall/basicData/customerInformation";
import corpType from "./components/index";
import { option } from "../commodityInformation/js/optionList";

export default {
  name: "index",
  components: {
    corpType,
    detailsPage
  },
  data() {
    return {
      treeData: [],
      corpTypeVisible: false,
      treeOption: {
        addBtn: false,
        menu: false,
        size: "small",
        props: {
          labelText: "标题",
          label: "title",
          value: "value",
        }
      },
      excelBox: false,
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "模板下载",
            prop: "excelTemplate",
            formslot: true,
            span: 24
          },
          {
            label: "模板上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            loadText: "模板上传中，请稍等",
            span: 24,
            propsHttp: {
              res: "data"
            },
            tip: "请上传 .xls,.xlsx 标准格式文件",
            action: "/api/blade-sales-part/corpsDesc/supplierImport?corpType=GYS"
          }
        ]
      },
      detailsOpen: false,
      loading: false,
      search: {},
      form: {},
      dataList: [],
      detailData: {},
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0,
        pageSizes: [10, 20, 30, 40, 50, 100, 200, 300, 400, 500]
      },
      key: 0,
      option: {},
      optionList: {
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        addBtn: false,
        index: true,
        span: 8,
        border: true,
        align: "center",
        // height: "auto",
        Height: '50',
        searchMenuPosition: "right",
        size: "small",
        menuWidth: 50,
        searchSpan: 8,
        searchIcon: true,
        searchIndex: 2,
        highlightCurrentRow: true,
        dialogWidth: "70%",
        column: [{
          label: '全称',
          prop: "cname",
          search: {
            fuzzy: true // 启用模糊搜索
          },
          props: {
            label: "cname",
            value: "id"
          },
          overHidden: true,
        }, {
          label: '供应商分类',
          prop: "corpsTypeName",
          overHidden: true,
        }, {
          label: '电话',
          prop: "tel",
          search: true,
          overHidden: true,
        }, {
          label: "业务员",
          prop: "salesmanId",
          search: true,
          type: "select",
          props: {
            label: "name",
            value: "id"
          },
          dicUrl: "/api/blade-user/client/salerList",
          filterable: true,
          overHidden: true
        }, {
          label: '备注',
          prop: "remarks",
          search: true,
          overHidden: true,
        }, {
          label: '是否启用',
          prop: 'enableOrNot',
          dicData: [{
            label: '是',
            value: 1
          }, {
            label: '否',
            value: 0
          }]
        }]
      }
    }
  },
  async created() {
    this.option = await this.getColumnData(this.getColumnName(262), this.optionList);
    this.key++
    getCorpType({ corpType: 'GYS' }).then(res => {
      console.log('看看');
      this.treeData = res.data.data
    });
    let i = 0;
    this.option.column.forEach(item => {
      if (item.search) i++
    })
    if (i % 3 !== 0) {
      const num = 3 - Number(i % 3)
      this.option.searchMenuSpan = num * 8;
      this.option.searchMenuPosition = "right";
    }

  },
  // activated() {
  //   this.$nextTick(() => {
  //     this.$refs.crud.doLayout()
  //   })
  // },
  methods: {
    addCorpType() {
      // this.$refs["corpType"].validate((valid, done) => {
      //   done();
      //   if (valid) {
      //     addCorpType({ ...this.form4, corpType: 'KH', status: 0 })
      //       .then(res => {
      //         this.$message.success("保存成功");
      //         this.getAllWorkDicts()
      //         this.corpTypeVisible = false
      //       })
      //   } else {
      //     return false;
      //   }
      // });
      // this.getAllWorkDicts()
      this.corpTypeVisible = false
    },
    corpTypeClosed() {
      this.refresh()
      console.log(234324);
      // this.reload = Math.random();
      // this.form4 = this.$options.data().form4
    },
    nodeClick(data) {
      this.search.corpsTypeId = data.value
      this.page.currentPage = 1;
      this.onLoad(this.page, this.search);
    },
    refresh(){
      getCorpType({ corpType: 'GYS' }).then(res => {
      console.log('看看');
      this.treeData = res.data.data
    });
    },
    derivation() {
      window.open(
        `/api/blade-sales-part/corpsDesc/supplierExport?${this.website.tokenHeader
        }=${getToken()}`
      );
    },
    uploadBefore(file, done, loading) {
      done();
      loading = true;
    },
    uploadAfter(res, done, loading, column) {
      this.excelBox = false;
      this.$message.success("导入成功！");
      this.refreshChange();
      loading = false;
      done();
    },
    check(row) {
      this.form = row
      this.detailsOpen = true
    },
    backToList(type) {
      this.form = {}
      this.detailsOpen = false
      if (type === 0) {
        this.detailData = {}
      }
      this.onLoad(this.page, this.search)
    },
    //刷新
    refreshChange() {
      this.onLoad(this.page, this.search)
    },
    rowDel(form, index) {
      this.$confirm('此操作将永久删除该行, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        remove({ id: form.id }).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.dataList.splice(index, 1);
          this.onLoad(this.page)
        })
      }).catch(() => {
      });
    },
    searchChange(params, done) {
        this.page.currentPage = 1
      this.onLoad(this.page, params)
      done();
    },
    onLoad(page, params = {}) {
      params = {
        ...params,
        cname: '',
        // {
        //   like: params.cname // 使用like操作符进行模糊匹配
        // },
        // supplierCategory: {
        //   like: params.supplierCategory // 使用like操作符进行模糊匹配
        // },
        current: page.currentPage,
        size: page.pageSize,
        corpType: "GYS",
        ...Object.assign(params, this.search)
      }
      this.loading = true
      getList(params).then(res => {
        this.dataList = res.data.data.records
        this.page.total = res.data.data.total
        this.loading = false
      }).finally(() => {
        this.loading = false
      })
    },
    //自定义列保存
    async saveColumnTwo(ref, option, optionBack, code) {
      /**
       * 已定义全局方法，直接使用，saveColumnData保存列数据方法,参数传值(表格名称，当前表格的option数据)
       * 已定义全局方法，直接使用，getColumnName方法用来获取枚举值，参数根据自己定义的code值获取中文名
       * 一定要执行异步操作，要等接口成功返回，才能执行下一行代码
       */
      const inSave = await this.saveColumnData(this.getColumnName(code), this[option]);
      if (inSave) {
        this.$message.success("保存成功");
        //关闭窗口
        this.$refs[ref].$refs.dialogColumn.columnBox = false;
      }
    },
    //自定义列重置
    async resetColumnTwo(ref, option, optionBack, code) {
      this[option] = this[optionBack];
      const inSave = await this.delColumnData(this.getColumnName(code), this[optionBack]);
      if (inSave) {
        this.$message.success("重置成功");
        this.$refs[ref].$refs.dialogColumn.columnBox = false;
      }
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-input-group__append {
  padding: 0 0px !important;
}

</style>
