<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="primary"
                   size="small"
                   icon="el-icon-add"
                   plain
                   @click="handleImport">导入
        </el-button>
      </template>
    </avue-crud>

    <el-dialog title="商品导入" @close="refreshChange"
               append-to-body
               :visible.sync="importCategoryBox"
               :before-close="handleClose"
               width="480px"
               heigh="40%">
      <el-form :model="form" label-width="80px">
        <el-form-item
          label="毛利:"
        >
          <el-input type="grossRate" v-model.number="grossRate" autocomplete="off" placeholder="请输入毛利(非必填)"></el-input>
        </el-form-item>
        <el-form-item label="分类:">
          <avue-cascader placeholder="请选择分类" check-strictly lazy :lazy-load="lazyLoad" v-model="categoryIdArr" :props="props" ></avue-cascader>
        </el-form-item>
        <el-form-item label="专区类型:">
          <el-select v-model="zoneType" placeholder="请选择专区类型">
            <el-option
              v-for="item in zoneTypeList"
              :key="item.dictKey"
              :label="item.dictValue"
              :value="item.dictKey">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="importSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="同品牌商品修改"
               append-to-body
               :before-close="handleClose"
               :visible.sync="importCheckBox"
               width="95%">
      <avue-crud :option="goodsOption"
                 :table-loading="goodsLoading"
                 :data="goodsData"
                 :page.sync="goodsPage"
                 :permission="permissionList"
                 @selection-change="goodsSelectionChange"
                 @refresh-change="goodsRefreshChange"
                 v-model="goodsForm"
                 ref="goodsCrud"
                 @on-load="onLoadGoods">
        <template slot="menuLeft">
          <el-button type="primary"
                     size="small"
                     plain
                     @click="modifyGoodsStateBatch(0)">下架
          </el-button>
        </template>
        <template slot="menuLeft">
          <el-button type="primary"
                     size="small"
                     @click="checkMe">导入商品
          </el-button>
        </template>
      </avue-crud>
    </el-dialog>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove, tree, zoneTypeOption, importGoods, getGoodsClassify} from "@/api/supplychain/wpsgoods";
  import {getList as getGoodsList, modifyState} from "@/api/redenvelopemall/goodsinfo";
  import {mapGetters} from "vuex";
  import {getByParentId} from "../../api/redenvelopemall/categoryinfo";
  import {importCheck} from "../../api/supplychain/wpsgoods";

  export default {
    data() {
      return {
        props: {
          label: "title",
          value: "key"
        },
        importCategoryBox: false,
        importCheckBox: false,
        zoneTypeList: [],
        categoryData: [],
        categoryIdArr: [],
        grossRate: '',
        zoneType: '',
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        goodsPage: {
          page: 10,
          currentPage: 1,
          total: 0,
          pageSizes: [10, 20, 30, 40, 50]
        },
        selectionList: [],
        option: {
          searchIcon: true,
          searchIndex: 3,
          menu:false,
          height:'auto',
          calcHeight: 30,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "主键",
              prop: "id",
              hide: true,
              rules: [{
                required: true,
                message: "请输入主键",
                trigger: "blur"
              }]
            },

            {
              label: "父级id",
              prop: "fatherGoodsId",
              hide: true,
              rules: [{
                required: true,
                message: "请输入父级id",
                trigger: "blur"
              }]
            },
            {
              label: "商品名称",
              prop: "goodsName",
              width: 250,
              search: true,
              rules: [{
                required: true,
                message: "请输入商品名称",
                trigger: "blur"
              }]
            },
            {
              label: "商品描述",
              prop: "goodsDescription",
              hide: true,
              rules: [{
                required: true,
                message: "请输入商品描述",
                trigger: "blur"
              }]
            },
            {
              label: "不发货地区",
              prop: "noDeliveryArea",
              hide: true,
              rules: [{
                required: true,
                message: "请输入不发货地区",
                trigger: "blur"
              }]
            },
            {
              label: "商品图片",
              prop: "goodsImage",
              addDisplay: false,
              viewDisplay: false,
              editDisplay: false,
              type: 'img',
              dataType: 'string',
              size: "large"
            },
            {
              label: "商品详情图",
              prop: "detailsImages",
              hide: true,
              rules: [{
                required: true,
                message: "请输入商品详情图",
                trigger: "blur"
              }]
            },
            {
              label: "商品banner图",
              prop: "bannerImages",
              hide: true,
              rules: [{
                required: true,
                message: "请输入商品banner图",
                trigger: "blur"
              }]
            },
            {
              label: "品牌id",
              prop: "brandId",
              hide: true,
              rules: [{
                required: true,
                message: "请输入品牌id",
                trigger: "blur"
              }]
            },
            {
              label: "品牌图标",
              prop: "brandIcon",
              hide: true,
              rules: [{
                required: true,
                message: "请输入品牌图标",
                trigger: "blur"
              }]
            },
            {
              label: "品牌名称",
              prop: "brandName",
              rules: [{
                required: true,
                message: "请输入品牌名称",
                trigger: "blur"
              }]
            },
            {
              label: "折扣",
              prop: "discount"
            },
            {
              label: "分类id",
              prop: "classId",
              hide: true,
              rules: [{
                required: true,
                message: "请输入分类id",
                trigger: "blur"
              }]
            },
            {
              label: "折扣",
              prop: "discountRange",
              hide: true,
              search: true,
              addDisplay: false,
              editDisplay: false,
              editDisabled: false,
              viewDisplay: false,
              type: "select",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=discount_range",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              dataType: "string",
            },
            {
              label: "商品进价",
              prop: "inPrice",
              rules: [{
                required: true,
                message: "请输入商品进价",
                trigger: "blur"
              }]
            },
            {
              label: "建议零售价",
              prop: "salePrice",
              width: 90,
              rules: [{
                required: true,
                message: "请输入建议零售价",
                trigger: "blur"
              }]
            },
            {
              label: "利润",
              prop: "profits",
              rules: [{
                required: true,
                message: "请输入利润",
                trigger: "blur"
              }]
            },
            {
              label: "一级分类",
              prop: "classDesc",
              rules: [{
                required: true,
                message: "请输入分类描述",
                trigger: "blur"
              }]
            },
            {
              label: "二级分类id",
              prop: "class2Id",
              hide: true,
              rules: [{
                required: true,
                message: "请输入二级分类id",
                trigger: "blur"
              }]
            },
            {
              label: "二级分类",
              prop: "class2Desc",
              rules: [{
                required: true,
                message: "请输入二级分类描述",
                trigger: "blur"
              }]
            },
            {
              label: "三级分类id",
              prop: "class3Id",
              hide: true,
              rules: [{
                required: true,
                message: "请输入三级分类id",
                trigger: "blur"
              }]
            },
            {
              label: "三级分类",
              prop: "class3Desc",
              rules: [{
                required: true,
                message: "请输入三级分类描述",
                trigger: "blur"
              }]
            },
            {
              label: "上架时间",
              prop: "startDatetime",
              hide: true,
              rules: [{
                required: true,
                message: "请输入上架时间",
                trigger: "blur"
              }]
            },
            {
              label: "下架时间",
              prop: "stopDatetime",
              hide: true,
              rules: [{
                required: true,
                message: "请输入下架时间",
                trigger: "blur"
              }]
            },

            {
              label: "创建时间",
              prop: "createTime",
              hide: true,
              rules: [{
                required: true,
                message: "请输入创建时间",
                trigger: "blur"
              }]
            },
            {
              label: "更新时间",
              prop: "updateTime",
              hide: true,
              rules: [{
                required: true,
                message: "请输入更新时间",
                trigger: "blur"
              }]
            },
            {
              label: "商品原价(吊牌)",
              prop: "originalPrice",
              hide: true,
              rules: [{
                required: true,
                message: "请输入商品原价(吊牌)",
                trigger: "blur"
              }]
            },
            {
              label: "状态",
              prop: "isShow",
              formatter:(val,value)=>{
                return value == '1' ? '上架' : '下架';
              },
            },
            {
              label: "是否导入",
              prop: "isImport",
              type: "select",
              search: true,
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=import_flag",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              dataType: "number",
            },
            {
              label: "分类",
              prop: "categoryIdArr",
              hide: true,
              search: true,
              lazy: true,
              rules: [{
                required: true,
                message: "请选择分类",
                trigger: "blur"
              }],
              type: "cascader",
              filterable: true,
              checkStrictly: true,
              lazyLoad(node, resolve) {
                let parentCode;
                let stop_level = 2;
                let level = node.level;
                let list = [];

                if (node.level === 0) {
                  getGoodsClassify(1).then((res) => {
                    list = res.data.data;
                    list = (list || []).map(ele => {
                      return Object.assign(ele, {
                        leaf: level >= stop_level
                      })
                    })
                    resolve(list)
                  })
                } else if (level == 1 || level == 2){
                  parentCode = node.data.c_code;
                  getGoodsClassify(level + 1, parentCode).then((res) => {
                    list = res.data.data;
                    list = (list || []).map(ele => {
                      return Object.assign(ele, {
                        leaf: level >= stop_level
                      })
                    })
                    resolve(list)
                  })
                } else {
                  resolve(list)
                }
              },
              props: {
                label: "c_name",
                value: "c_code"
              },
            },
          ]
        },
        data: [],
        goodsLoading: true,
        goodsData: [],
        goodsForm: {},
        brandList: [],
        goodsSelectionList: [],
        goodsOption: {
          height: 'auto',
          calcHeight: 30,
          menu: false,
          border: true,
          index: false,
          viewBtn: false,
          delBtn:false,
          editBtn: false,
          selection: true,
          dialogClickModal: false,
          labelWidth: 150,
          column: [
            {
              label: "主键",
              prop: "id",
              hide: true,
              addDisplay: false,
              viewDisplay: false,
              editDisplay: false,
              editDisabled: true,
              rules: [{
                required: true,
                message: "请输入主键",
                trigger: "blur"
              }]
            },
            {
              label: "商品编号",
              prop: "goodsNo",
              addDisplay: false,
              editDisabled: true,
              rules: [{
                required: true,
                message: "请输入商品编号",
                trigger: "blur"
              }]
            },
            {
              label: "商品名称",
              prop: "goodsName",
              width: 280,
              rules: [{
                required: true,
                message: "请输入商品名称",
                trigger: "blur"
              }]
            },
            {
              label: "商品封面",
              prop: "goodsCover",
              addDisplay: false,
              viewDisplay: false,
              editDisplay: false,
              type: 'img',
            },
            {
              label: "品牌",
              prop: "brandDesc",
            },
            {
              label: "协议价",
              prop: "agreementPrice",
              precision: 2,
              type: "number",
              formatter:(val,value)=>{
                return Number(value).toFixed(2);
              },
            },
            {
              label: "毛利率",
              prop: "promotionRate",
              addDisplay: false,
              editDisplay: false,
              editDisabled: true,
              formatter:(val,value)=>{
                return value + "%";
              },
            },
            {
              label: "销售价",
              prop: "salePrice",
              precision: 2,
              type: "number",
              formatter:(val,value)=>{
                return Number(value).toFixed(2);
              },
              rules: [{
                required: true,
                message: "请输入销售价",
                trigger: "blur"
              }],
              blur: ({value,column}) => {
                console.log('失去焦点',value,column)
              },
            },
            {
              label: "商品状态",
              prop: "isSale",
              formatter:(val,value)=>{
                return value == '1' ? '上架' : '下架';
              },
            },
            {
              label: "商品来源",
              prop: "source",
              editDisabled: true,
              type: "select",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=third_source",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              dataType: "number",
            },
            {
              label: "专区类型",
              prop: "zoneType",
              rules: [{
                required: true,
                message: "请选择专区类型",
                trigger: "blur"
              }],
              type: "select",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=zone_type",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              dataType: "number",
            },
          ]
        }
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.wpsgoods_add, false),
          viewBtn: this.vaildData(this.permission.wpsgoods_view, false),
          delBtn: this.vaildData(this.permission.wpsgoods_delete, false),
          editBtn: this.vaildData(this.permission.wpsgoods_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      goodsSelectionChange(list) {
        this.goodsSelectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      goodsSelectionClear() {
        this.goodsSelectionList = [];
        this.$refs.goodsCrud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      goodsRefreshChange() {
        this.onLoadGoods(this.goodsPage);
      },
      onLoad: function (page, params = {}) {
        this.loading = true;
        let arr = this.query.categoryIdArr;
        if (arr) {
          if (arr.length == 1) {
            this.query.classId = arr[0]
          }
          if (arr.length == 2) {
            this.query.class2Id = arr[1]
          }
          if (arr.length == 3) {
            this.query.class3Id = arr[2]
          }
          delete this.query.categoryIdArr
        }
        if (this.query.discountRange) {
          let arr = this.query.discountRange.split("-");
          this.query.minDiscount = arr[0];
          this.query.maxDiscount = arr[1];
          delete this.query.discountRange;
        }
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },
      handleImport() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        // let brandSet = new Set();
        // this.selectionList.forEach(e => {
        //   brandSet.add(e.brandName);
        // })
        // const loading = this.$loading({
        //   lock: true,
        //   text: '导入校验中...',
        //   spinner: 'el-icon-loading',
        //   background: 'rgba(0, 0, 0, 0.7)'
        // });
        // importCheck(brandSet).then(res => {
        //   loading.close();
        //   let list = res.data.data;
        //   console.log("list - ", list)
        //   if (list && list.length > 0) {
        //     this.brandList = list;
        //     this.importCheckBox = true;
        //     // this.$message.warning("有同品牌商品，请处理");
        //     this.goodsRefreshChange();
        //   } else {
        //     this.importCategoryBox = true;
        //     tree().then(res => {
        //       this.categoryData = res.data.data
        //     });
        //     zoneTypeOption().then(res => {
        //       this.zoneTypeList = res.data.data;
        //     })
        //   }
          this.importCategoryBox = true;
          tree().then(res => {
            this.categoryData = res.data.data
          });
          zoneTypeOption().then(res => {
            this.zoneTypeList = res.data.data;
          })
        // }).catch(() => {
        //   loading.close();
        // })
      },
      lazyLoad(node, resolve) {
        let parentId;
        let stop_level = 2;
        let level = node.level;
        let list = [];

        if (node.level === 0) {
          parentId = 0;
          getByParentId(0).then((res) => {
            list = res.data.data;
            list = (list || []).map(ele => {
              return Object.assign(ele, {
                leaf: level >= stop_level
              })
            })
            resolve(list)
          })
        } else {
          parentId = node.data.id;
          getByParentId(node.data.id).then((res) => {
            list = res.data.data;
            list = (list || []).map(ele => {
              return Object.assign(ele, {
                leaf: level >= stop_level
              })
            })
            resolve(list)
          })
        }
      },
      handleClose() {
        this.importCategoryBox = false;
        this.importCheckBox = false;
        this.zoneType = '';
        this.categoryIdArr = [];
        this.grossRate = '';
      },
      importSubmit() {
        if (this.categoryIdArr.length == 0) {
          this.$message.warning("请选择分类");
          return;
        }
        if (this.zoneType == '') {
          this.$message.warning("请选择专区类型");
          return;
        }
        const loading = this.$loading({
          lock: true,
          text: '导入中，请稍等...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        let fatherIds = [];
        this.selectionList.forEach(ele => {
          fatherIds.push(ele.fatherGoodsId);
        });
        importGoods(fatherIds.join(","), this.grossRate, this.categoryIdArr.join("-") + "-", this.zoneType).then(() => {
          loading.close();
          this.onLoad(this.page, this.query);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.importCheckBox = false;
          this.selectionClear()
          this.handleClose()
        }).catch(() => {
          loading.close();
        });
      },
      onLoadGoods(page) {
        console.log("onloadgoods-----")
        this.goodsLoading = true;
        // this.goodsCategoryId = this.query.categoryIdArr.join(",");
        let param = {isSale:1, source: "1", brandIds: this.brandList};

        getGoodsList(page.currentPage, page.pageSize, param).then(res => {
          const data = res.data.data;
          this.goodsPage.total = data.total;
          this.goodsData = data.records;
          this.goodsLoading = false;
          this.goodsSelectionClear();
        });
      },
      modifyGoodsStateBatch(state) {
        if (this.goodsSelectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定修改数据?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
            const loading = this.$loading({
              lock: true,
              text: '修改中，请稍等...',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            });
            let goodsIds = [];
            this.goodsSelectionList.forEach(e => {
              goodsIds.push(e.id);
            })
            modifyState(goodsIds.join(","), state).then(() => {
              loading.close();
              this.onLoadGoods(this.goodsPage);
              this.$message({
                type: "success",
                message: "操作成功!"
              });
              this.goodsSelectionClear()
            }).catch(() => {
              loading.close();
            });
          })
      },
      checkMe() {
        this.importCategoryBox = true;
        tree().then(res => {
          this.categoryData = res.data.data
        });
        zoneTypeOption().then(res => {
          this.zoneTypeList = res.data.data;
        })
      }
    }
  };
</script>

<style>
</style>
