<template>
  <div>
    <basic-container>
      <el-row>
        <el-col :span="4">
          <avue-tree :option="treeOption" :data="treeData" @node-click="nodeClick" style="height:73vh;"
                     @save="corpTypeVisible = true">
          </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" @selection-change="selectionChange"
                     :before-open="beforeOpen"
                     @row-update="rowUpdate" @search-change="searchChange" @refresh-change="refreshChange"
                     @resetColumn="resetColumnTwo('crud', 'option', 'optionList', 273.1)"
                     @saveColumn="saveColumnTwo('crud', 'option', 'optionList', 273.1)" :page.sync="page">
            <template slot="filesListForm">
              <span style="font-size: 12px;">(图片文件像素推荐700X750，有且只允许有一张主图，其余均为副图)</span>
              <c-upload :data="form.filesList" display basic deleteUrl="/api/blade-sales-part/productLaunchFiles/remove"
                        :enumerationValue="160"/>
            </template>
            <template slot="detailsTextForm">
              <avue-ueditor v-model="form.detailsText" :options="optionsUeditor"></avue-ueditor>
            </template>
            <template slot-scope="{type,size,row,index}" slot="menu">
              <el-button :size="size" :type="type" :disabled="row.upAndDownShelves" @click="$refs.crud.rowEdit(row, index)">编辑
              </el-button>
              <el-tooltip :content="`${row.upAndDownShelves == 0?'上架':'下架'}`" placement="top">
                <el-switch
                    style="margin-left: 10px"
                    v-model="row.upAndDownShelves"
                    @change="check(row)"
                    :active-value="1"
                    :inactive-value="0">
                </el-switch>
              </el-tooltip>
            </template>
            <template slot-scope="{type,size,row,$index}" slot="menuLeft">
              <el-button class="el-icon-document-copy" :disabled="selectionList.length === 0" type="primary"
                         size="small"
                         @click="change(row, 'up')">批量上架
              </el-button>
              <el-button class="el-icon-document-copy" :disabled="selectionList.length === 0" type="danger" size="small"
                         @click="change(row, 'down')">批量下架
              </el-button>
              <!--<el-button class="el-icon-bottom" type="warning" size="small" @click="excelBox = true">-->
              <!--  导入-->
              <!--</el-button>-->
            </template>
          </avue-crud>
        </el-col>
      </el-row>
    </basic-container>
    <el-dialog title="添加产品" append-to-body :visible.sync="excelBox" :close-on-click-modal="false" width="555px">
      <avue-form :option="excelOption" v-model="excelForm" :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>
  </div>
</template>

<script>
import {
  getList,
  submit,
  batchOperationProductLaunch,
  getDetail, listAll
} from "@/api/tirePartsMall/basicData/listingManagement/index.js";
import {getToken} from "@/util/auth";
import fa from "element-ui/src/locale/lang/fa";

export default {
  name: "index",
  data() {
    return {
      optionsUeditor: {
        //普通上传地址
        // action:'https://avuejs.com/imgupload',
        action: "/api/blade-resource/oss/endpoint/put-file",
        headers: {"Blade-Auth": "Bearer " + getToken()},
        props: {
          res: "data",
          url: 'link'
        }
      },
      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/productLaunch/import-productLaunch"
          }
        ]
      },
      treeOption: {
        addBtn: false,
        menu: false,
        size: "small",
        props: {
          labelText: "标题",
          label: "cname",
          value: "id",
        }
      },
      excelBox: false,
      corpTypeVisible: false,
      treeData: [],
      loading: false,
      search: {},
      form: {},
      dataList: [],
      selectionList: [],
      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,
        updateBtnText:'保存',
        selection: true,
        height: "auto",
        searchMenuPosition: "right",
        align: "center",
        menuWidth: 100,
        updateBtnText:'保存',
        searchSpan: 8,
        searchIcon: true,
        searchIndex: 2,
        highlightCurrentRow: true,
        dialogWidth: "70%",
        column: [{
          label: '轮胎名称',
          prop: 'cname',
          search: true,
          disabled: true,
          overHidden: true,
        }, {
          label: '规格型号',
          prop: 'specificationAndModel',
          search: true,
          disabled: true,
          overHidden: true,
        },{
          label: '花纹',
          prop: 'brandItem',
          disabled: true,
          overHidden: true,
        }, {
          label: '公司',
          prop: 'salesCompanyId',
          disabled: true,
          overHidden: true,
          type: 'select',
          props: {
            label: 'fullName',
            value: 'id'
          },
          dicUrl: '/api/blade-system/dept/top-list'
        }, {
          label: '库存',
          prop: 'inventory',
          disabled: true,
          overHidden: true,
        }, {
          label: '产品状态',
          prop: 'upAndDownShelves',
          filterable: true,
          display: false,
          search: true,
          hide: true,
          disabled: true,
          showColumn: false,
          type: 'select',
          dicData: [{
            label: "上架",
            value: 1
          }, {
            label: "下架",
            value: 0
          }]
        }, {
          label: "品牌",
          prop: "brandName",
          disabled: true,
          overHidden: true,
        }, {
          label: "售价1",
          prop: "priceOne",
          hide: true,
          showColumn: false,
          overHidden: true,
        }, {
          label: "售价2",
          prop: "priceTwo",
          hide: true,
          showColumn: false,
          overHidden: true,
        }, {
          label: "售价3",
          prop: "priceThree",
          hide: true,
          showColumn: false,
          overHidden: true,
        }, {
          label: "售价4",
          prop: "priceFour",
          hide: true,
          showColumn: false,
          overHidden: true,
        }, {
          label: "共享成本",
          prop: "shareCost",
          overHidden: true,
        }, {
          label: "来源公司",
          prop: "sourceCompanyId",
          hide: true,
          search: true,
          showColumn: true,
          overHidden: true,
          disabled: true,
          type: 'select',
          props: {
            label: 'fullName',
            value: 'id'
          },
          dicUrl: '/api/blade-system/dept/top-list'
        }, {
          label: "详情附件",
          prop: "filesList",
          hide: true,
          showColumn: false,
          overHidden: true,
          span: 24,
        }, {
          label: "轮胎详情",
          prop: "detailsText",
          hide: true,
          span: 24,
          showColumn: false,
          overHidden: true,
        }]
      }
    }
  },
  activated() {
    listAll().then(res=>{
      this.treeData = res.data.data
    })
    this.onLoad(this.page, this.search)
  },
  async created() {
    this.option = await this.getColumnData(this.getColumnName(273.1), this.optionList);
    this.key++
    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";
    }
  },
  methods: {
    derivation() {
      window.open(
        `/api/blade-sales-part/productLaunch/export-productLaunch?${this.website.tokenHeader
        }=${getToken()}`
      );
    },
    uploadAfter(res, done, loading, column) {
      this.excelBox = false;
      this.refreshChange();
      done();
    },
    nodeClick(data) {
      this.search.brandId = data.id
      this.page.currentPage = 1;
      this.onLoad(this.page, this.search);
    },
    //刷新
    refreshChange() {
      this.onLoad(this.page, this.search)
    },
    searchChange(params, done) {
      done();
      this.onLoad(this.page, params)
    },
    selectionChange(list) {
      this.selectionList = list
    },
    //打开表单前
    beforeOpen(done, type) {
      // 查看和编辑逻辑
      if (['view', 'edit'].includes(type)) {
        getDetail({id: this.form.id}).then(res => {
          this.form = res.data.data
          done();
        })
      }
    },
    //编辑确定
    rowUpdate(form, index, done, loading) {
      if (this.form.filesList.length > 0) {
        let flag = this.form.filesList.some(item => {
          return item.$version == '主图'
        })
        if (!flag) {
          this.$message.warning('请选择主图')
          done()
          return
        }
      }
      submit({
        ...this.form
      }).then(res => {
        this.$message.success("修改成功")
        this.onLoad(this.page, this.search)
        done()
      }).catch((err) => {
        loading()
      })
      // submit({
      //   ...form
      // }).then(res => {
      //   this.onLoad(this.page, this.search)
      //   done()
      // }).catch(() => {
      //   loading()
      // })
    },
    check(row) {
      batchOperationProductLaunch({
        flag: row.upAndDownShelves,
        ids: row.id
      }).then(res => {
        this.onLoad(this.page, this.search)
      })
    },
    change(row, type) {
      let data = []
      for (let item of this.selectionList) {
        data.push(item.id)
      }
      if (type === "up") {
        // for (let item of this.selectionList) {
        //   if (!Number(item.salesPrice)) return this.$message.error("上架失败,商城价格不能为0")
        // }
        this.$confirm('是否确认全部上架?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          batchOperationProductLaunch({
            flag: 1,
            ids: data.join(",")
          }).then(res => {
            this.onLoad(this.page, this.search)
          })
        })
      } else if (type === "down") {
        this.$confirm('是否确认全部下架?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          batchOperationProductLaunch({
            flag: 0,
            ids: data.join(",")
          }).then(res => {
            this.onLoad(this.page, this.search)
          })
        })
      }
    },
    onLoad(page, params = {}) {
      params = {
        ...params,
        current: page.currentPage,
        size: page.pageSize,
        ...Object.assign(params, this.search),
        billType: 1
      }
      this.loading = true
      getList(params).then(res => {
        this.dataList = res.data.data.records
        this.page.total = res.data.data.total
        this.$nextTick(() => {
          this.$refs.crud.doLayout();
        });
        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.$nextTick(() => {
          this.$refs.crud.doLayout();
        });
        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;
        this.$nextTick(() => {
          this.$refs.crud.doLayout();
        });
      }
    }
  }
}
</script>

<style scoped></style>
