<template>
  <div>
    <basic-container v-show="show" class="page-crad">
      <el-row>
        <el-col :span="4">
          <avue-tree :option="treeOption" :data="treeData" @node-click="nodeClick" style="height:82vh;">
            <template slot="addBtn">
              <el-tooltip class="item" effect="dark" content="新建分类" placement="top">
                <i class="el-icon-setting" @click="goodsTypeVisible = true"
                  style="font-size:18px;line-height: 1px;width: 20px;padding:10px;"></i>
              </el-tooltip>
            </template>
          </avue-tree>
        </el-col>
        <el-col :span="20">
          <avue-crud ref="crud" :option="option" :data="dataList" :page.sync="page" :search.sync="search" :key="key"
            @search-change="searchChange" @current-change="currentChange" @size-change="sizeChange"
            @refresh-change="refreshChange" @on-load="onLoad" :table-loading="loading" @saveColumn="saveColumn"
            @resetColumn="resetColumn" :cell-style="cellStyle" @search-criteria-switch="searchCriteriaSwitch">
            <template slot="menuLeft">
              <el-button type="primary" size="mini" @click.stop="newAdd()">新建产品
              </el-button>
              <el-button type="primary" size="mini" icon="el-icon-bottom" @click="excelBox = true">导入
              </el-button>
              <el-button type="primary" size="mini" icon="el-icon-top" @click="outExport">导出
              </el-button>
              <el-button type="primary" size="mini" icon="el-icon-top" @click="synchronization">同步商品信息
              </el-button>
            </template>
            <template slot="enableOrNot" slot-scope="{row,index,disabled}">
              <div v-if="row.enableOrNot === 1">是</div>
              <div v-else style="color: red">否</div>
            </template>
            <template slot-scope="{ row, index }" slot="cname">
              <span style="color: #409EFF;cursor: pointer" @click.stop="editOpen(row, 2)">{{ row.cname }}
              </span>
            </template>
            <template slot-scope="{ row, index }" slot="menu">
              <!-- <el-button  :size="small" :type="text"
              @click.stop="rowDel(row, index)" v-if="row.status != 0">删除</el-button> -->
              <!-- <el-tooltip class="item" effect="dark" content="删除" placement="top">
                <i class="tradingIcon icon-del"  />
              </el-tooltip> -->
              <!-- <el-tooltip class="item" effect="dark" content="新建销售订单" placement="top">
            <i class="tradingIcon icon-add" />
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="编辑" placement="top">
            <i class="tradingIcon icon-edit" />
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="收款" placement="top">
            <i class="tradingIcon icon-proceeds" />
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="发货" placement="top">
            <i class="tradingIcon icon-deliver" />
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="对账" placement="top">
            <i class="tradingIcon icon-reconciliation" />
          </el-tooltip> -->
              <!-- <el-button type="text" size="small" @click.stop="editOpen(row, 2)">
            查看
          </el-button>
          <el-button type="text" size="small" @click.stop="rowDel(row, index)">
            删除
          </el-button> -->
              <el-button type="text" size="small" @click.stop="rowDel(row, index)" v-if="row.status != 0"
                :disabled="row.enableOrNot">
                删除
              </el-button>
            </template>
          </avue-crud>
        </el-col>
      </el-row>
    </basic-container>
    <details-page v-if="!show" @goBack="goBack()" :detailData="detailData" />
    <el-dialog title="设置产品分类" v-dialogDrag :visible.sync="goodsTypeVisible" class="avue-dialog" width="80%"
      append-to-body @closed="goodsTypeClosed">
      <span>
        <!--<goods-type></goods-type>-->
        <corp-type></corp-type>
        <!-- <avue-form :key="reload" ref="goodsType" v-model="form2" :option="option2" style="margin-top:20px">
        </avue-form> -->
      </span>
      <div class="avue-dialog__footer">
        <el-button @click="goodsTypeVisible = false" size="mini">取 消</el-button>
        <el-button @click="saveGoodstype" type="primary" size="mini">确 定</el-button>
      </div>
    </el-dialog>
    <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 detailsPage from "./detailsPage";
import { option } from "./js/optionList";
import { getList, remove, getCorpType, synchronization } from "@/api/tirePartsMall/basicData/commodityInformation";
import { getToken } from "@/util/auth";
// import goodsType from '@/components/goodsType/index'
import corpType from './components/index'
import { isProcurement } from "@/api/basicData/configuration";

export default {
  name: "index",
  data() {
    return {
      goodsTypeVisible: false,
      src: '',
      key: 0,
      show: true,
      loading: false,
      search: {},
      detailData: {},
      dataList: [],
      selectionList: [],
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0,
        pageSizes: [10, 20, 30, 40, 50, 100, 200, 300, 400, 500]
      },
      option: {},
      treeData: [],
      form2: {},
      option2: {
        menuBtn: false,
        labelWidth: 80,
        column: [
          {
            label: "分类名称",
            prop: "cname",
            rules: [
              {
                required: true,
                message: "",
                trigger: "blur"
              }
            ],
            span: 24,
          },
          {
            label: "上级类型",
            prop: "parentId",
            dicData: [],
            type: "tree",
            props: {
              label: "title",
              value: "id"
            },
            span: 24,
          }
        ]
      },
      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/goodsDesc/import-desc"
          }
        ]
      }
    };
  },
  components: {
    detailsPage,
    corpType,
    // goodsType
  },
  async created() {
    this.option = await this.getColumnData(this.getColumnName(217), option);
    this.key++
    isProcurement({ "param": "whether.model" }).then(res => {
      if (res.data.data == 1) {
        this.findObject(this.option.column, "brandItem").label = '规格型号1'
        this.findObject(this.option.column, "explosionProof").search = false
      }
    })
    this.getAllWorkDicts()
  },
  activated() {
    this.$refs.crud.refreshTable();
  },
  methods: {
    getAllWorkDicts() {
      // getCorpsAll().then(res => {
      //   this.findObject(this.option.column, "cname").dicData = res.data.data;
      //   this.findObject(this.option.column, "ids").dicData = res.data.data;
      // })
      // "/api/blade-system/dict-biz/dictionary?code=label",
      // this.getWorkDicts("label").then(res => {
      //   this.findObject(this.option.column, "label").dicData = res.data.data;
      // });
      // this.getWorkDicts("unit").then(res => {
      //   this.findObject(this.option.column, "unit").dicData = res.data.data;
      // });
      // this.getWorkDicts("goods_status").then(res => {
      //   this.findObject(this.option.column, "status").dicData = res.data.data;
      // });
      // getAllgoods().then(res => {
      //   this.findObject(this.option.column, "cname").dicData = res.data.data
      // });
      getCorpType({ corpType: 'SP' }).then(res => {
        this.treeData = res.data.data;
        // this.findObject(this.option2.column, "parentId").dicData = res.data.data;
      });
      this.$refs.crud.init();
    },
    searchCriteriaSwitch(type) {
      this.$refs.crud.getTableHeight();
    },
    derivation() {
      window.open(
        `/api/blade-sales-part/goodsDesc/export-template?${this.website.tokenHeader
        }=${getToken()}`
      );
    },
    //导出
    outExport() {
      let config = { params: { ...this.search } }
      if (config.params) {
        for (const propName of Object.keys(config.params)) {
          const value = config.params[propName];
          if (value !== null && typeof (value) !== "undefined") {
            if (value instanceof Array) {
              for (const key of Object.keys(value)) {
                let params = propName + '[' + key + ']';
                config.params[params] = value[key]
              }
              delete config.params[propName]
            }
          }
        }
      }
      const routeData = this.$router.resolve({
        path: '/api/blade-sales-part/goodsDesc/exportGoodsList',      //跳转目标窗口的地址
        query: {
          ...config.params,    //括号内是要传递给新窗口的参数
          identification: this.url
        }
      })
      window.open(routeData.href.slice(1, routeData.href.length) + '&' + `${this.website.tokenHeader}=${getToken()}`);
    },
    synchronization() {
      this.loading = true;
      synchronization().then(res => {
        this.$nextTick(() => {
          this.$refs.crud.doLayout();
          this.$refs.crud.dicInit();
        });
        this.$message.success(res.data.msg);
      }).finally(() => {
        this.loading = false;
      });
    },
    uploadAfter(res, done, loading, column) {
      this.excelBox = false;
      this.refreshChange();
      done();
    },
    cellStyle() {
      return "padding:0;height:40px;";
    },
    //点击搜索按钮触发
    searchChange(params, done) {
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    refreshChange() {
      this.onLoad(this.page, this.search);
    },
    newAdd() {
      this.detailData = {
        goodsTypeId: this.search.goodsTypeId
      };
      this.show = false;
    },
    saveGoodstype() {
      // this.$refs["goodsType"].validate((valid, done) => {
      //   done();
      //   if (valid) {
      //     goodsTypesubmit({ ...this.form2, status: 0 }).then(res => {
      //       this.getAllWorkDicts()
      //     })
      //     this.goodsTypeVisible = false
      //   } else {
      //     return false;
      //   }
      // });
      this.getAllWorkDicts()
      this.goodsTypeVisible = false
    },
    goodsTypeClosed() {
      // this.reload = Math.random();
      // this.form2 = this.$options.data().form2
    },
    nodeClick(data) {
      this.search.goodsTypeId = data.value
      this.page.currentPage = 1;
      this.onLoad(this.page, this.search);
    },
    onLoad(page, params = {}) {
      let data = this.deepClone(Object.assign(params, this.search));
      data.whetherIntegral='0'
      this.loading = true;
      getList({
        ...data,
        current: page.currentPage,
        size: page.pageSize,
      }).then(res => {
        console.log(123214);
        this.dataList = res.data.data.records ? res.data.data.records : [];
        this.page.total = res.data.data.total;
        this.$nextTick(() => {
          this.$refs.crud.doLayout();
          this.$refs.crud.dicInit();
        });
      }).finally(() => {
        this.loading = false;
      });
    },
    editOpen(row, status) {
      this.detailData = {
        id: row.id,
        status: status
      };
      this.show = false;
    },
    currentChange(val) {
      this.page.currentPage = val;
    },
    sizeChange(val) {
      this.page.currentPage = 1;
      this.page.pageSize = val;
    },
    rowDel(row, index, done) {
      this.$confirm("确定删除数据?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        remove({ id: row.id }).then(res => {
          if (res.data.code == 200) {
            this.$message({
              type: "success",
              message: "删除成功!"
            });
            this.onLoad(this.page, this.search);
          }
        });
      });
    },
    async saveColumn() {
      const inSave = await this.saveColumnData(
        this.getColumnName(217),
        this.option
      );
      isProcurement({ "param": "whether.model" }).then(res => {
        if (res.data.data == 1) {
          this.findObject(this.option.column, "brandItem").label = '规格型号1'
          this.findObject(this.option.column, "explosionProof").search = false
        }
      })
      if (inSave) {
        this.$nextTick(() => {
          this.$refs.crud.doLayout();
          this.$refs.crud.dicInit();
        });
        this.$message.success("保存成功");
        //关闭窗口
        this.$refs.crud.$refs.dialogColumn.columnBox = false;
      }
    },
    async resetColumn() {
      this.option = option;
      const inSave = await this.delColumnData(this.getColumnName(217), option);
      isProcurement({ "param": "whether.model" }).then(res => {
        if (res.data.data == 1) {
          this.findObject(this.option.column, "brandItem").label = '规格型号1'
          this.findObject(this.option.column, "explosionProof").search = false
        }
      })
      if (inSave) {
        this.$nextTick(() => {
          this.$refs.crud.doLayout();
          this.$refs.crud.dicInit();
        });
        this.getAllWorkDicts()
        this.$message.success("重置成功");
        this.$refs.crud.$refs.dialogColumn.columnBox = false;
      }
    },
    //返回列表
    goBack() {
      this.detailData = this.$options.data().detailData;
      this.show = true;
      this.onLoad(this.page, this.search);
    },
  }
}
</script>

<style lang="scss" scoped>
.page-crad ::v-deep .basic-container__card {
  height: 94.2vh;
}

::v-deep .el-input-group__append {
  padding: 0 0px !important;
}

.stat-td {
  text-align: center;
  position: relative;
}

.stat-img {
  width: 95%;
  height: 100px;
}

.stat-tip {
  position: absolute;
  left: 15px;
  top: 5px;

  .money {
    color: #fff;
    font-size: 28px;
    text-align: left;
    font-weight: 600;
  }

  .title {
    color: #fff;
    font-size: 14px;
    text-align: left;
    margin-top: 5px;
    margin-bottom: 0px;
  }
}
</style>
