<template>
  <div class="choice-b" ref="choiceB">
    <basic-container>
      <!-- 在线选品 -->
      <avue-form :option="option" v-model="form" @submit="submit" ref="avueForm">
        <template slot-scope="{disabled,size}" slot="group_id">
          <el-button type="text" v-for="(ite, k) in activityList" :key="k">{{ite.name}}</el-button>
        </template>
        <template slot-scope="scope" slot="gross_profit_rate">
          <k-form-item ref="gross_profit_rateFormItem" :scope="scope" end-str="%"/>
        </template>
        <template slot-scope="scope" slot="promote_rate">
          <k-form-item ref="promote_rateFormItem" :scope="scope" end-str="%"/>
        </template>
        <template slot-scope="scope" slot="agreement_price">
          <k-form-item ref="agreement_priceFormItem" :scope="scope" />
        </template>
        <template slot-scope="scope" slot="discount">
          <k-form-item ref="discountFormItem" :scope="scope" end-str="折"/>
        </template>
      </avue-form>

      <div class="good-li" v-loading="loading" v-if="goodList.length > 0">
        <goods-choice v-for="(item, l) in goodList" :key="l" :item="item" @checkChange="checkChange"></goods-choice>
      </div>
      <avue-empty v-else/>
      <div style="height: 100px;"></div>
    </basic-container>
    <div class="operation" :style="'width: '+ bodyWidth + 'px;'">
      <basic-container>
        <avue-form :option="imOption" v-model="importForm" ref="importForm">
          <template slot-scope="scope" slot="a165750701340472520">
             <el-button type="primary" @click="importSubmit" >导入商品({{selectGood.length}})</el-button>
             <el-button type="warning" @click="selectGood = []">清空选择</el-button>
             <!-- <el-button type="primary">导入全部筛选商品({{total}})</el-button> -->
          </template>
          <template slot-scope="scope" slot="a165750701570373941">
             <div class="paging">
               <el-pagination
                 background
                 layout="total, sizes, prev, pager, next, jumper"
                 :page-sizes="[20, 30, 50, 80, 100]"
                 :total="total"
                 :page-size="form.limit"
                 :page-count="form.page"
                 @current-change="currentChange"
                 @size-change="sizeChange"></el-pagination>
             </div>
          </template>
        </avue-form>
      </basic-container>
    </div>
  </div>
</template>

<script>
  import {getGoodsStorageList} from "@/api/redenvelopemall/supplyChain";
  // import {getLazyList, getCategoryTree, getDetail, add, update, remove, updateBatch, getByParentId} from "@/api/redenvelopemall/categoryinfo";
  import kFormItem from './kFormItem'
  import { getList, getActivityLists, getByParentId, importGoods} from '../../api/polymerize/choice'
  import goodsChoice from '../../components/goods-choice/main'
  let dicFormatter = data => {
    data.data.push({ dictKey: "k-k", dictValue: "自定义区间"})
    return data.data
  }
  export default {
    components: {
      kFormItem,
      goodsChoice
    },
    data() {
      let self = this;
      return {
        form: {
          source: '1',
          page: 1,
          limit: 20,
        },
        option: {
          column: [
            {type: 'select',label: '平台来源',
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=goods_source",
              change(param) {
                self.sourceChange(param.value)
              },
              span: 12, display: true, props: {label: "dictValue",value: "dictKey"}, prop: 'source'},
            {type: 'cascader', label: '类目', span: 12, display: true, cascaderIndex: 1, showAllLevels: true, props: {label: 'title', value: 'id'}, prop: 'category_id',
              lazy: true,
              checkStrictly: true,
              lazyLoad(node, resolve) {
                let level = node.level;
                let param = 0;
                if(level == 0) param = 0;
                else param = node.data.id;
                self.loadinit(param, resolve);
              }
            },
            {type: 'select',label: '毛利率',
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=gross_profit_rate", dicFormatter,
              span: 6,display: true, props: {label: "dictValue",value: "dictKey" },prop: 'gross_profit_rate'},
            {type: 'select',label: '利润率',
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=gross_profit_rate", dicFormatter,
              span: 6,display: true,props: {label: "dictValue",value: "dictKey"},prop: 'promote_rate'},
            {type: 'select',label: '协议价',
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=propose_price", dicFormatter,
              span: 6,display: true,props: {label: "dictValue",value: "dictKey"}, prop: 'agreement_price'},
            {type: 'select',label: '指导价',
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=propose_price",
              span: 6, display: true, props: {label: "dictValue",value: "dictKey"}, prop: 'guide_price'},
            {type: 'select',label: '营销价',
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=propose_price",
              span: 6, display: true, props: {label: "dictValue", value: "dictKey"}, prop: 'activity_price'},
            {type: 'select',label: '折扣',
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=discount_range", dicFormatter,
              span: 6,display: true,props: {label: "dictValue", value: "dictKey"}, prop: 'discount'},
            {type: 'select',label: '是否包邮',
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=free_postage",
              span: 6,display: true,props: {label: "dictValue",value: "dictKey"},prop: 'is_free_shipping', dataType: "number"},

            {type: 'input',label: '营销活动',span: 12,display: true, prop: 'group_id'},
            {type: 'input',label: '关键词',span: 12,display: true, prop: 'search_words'}
          ],
          labelPosition: 'right',
          labelSuffix: '：',
          labelWidth: 90,
          gutter: 0,
          menuBtn: true,
          submitBtn: true,
          submitText: '查询',
          emptyBtn: true,
          emptyText: '清空',
          menuPosition: 'center',
          loading: false
        },
        total: 0,
        goodList: [],
        activityList: [],
        bodyWidth: 0,
        selectGood: [],
        importForm: {},
        imOption: {
          column: [
            {type: 'input', label: '毛利率',span: 8, display: true, prop: 'grossRate',
              rules: [{ required: true, message: "请输入毛利率",trigger: "blur"}]
            },
            {type: 'cascader', label: '类目', span: 8, display: true, cascaderIndex: 1, showAllLevels: true, props: {label: 'title', value: 'id'}, prop: 'categoryIds',
              lazy: true,
              checkStrictly: true,
              lazyLoad(node, resolve) {
                let level = node.level;
                let param = 0;
                if(level == 0) param = 0;
                else param = node.data.id;
                self.loadinit(param, resolve);
              },
              rules: [{ required: true, message: "请选择类目",trigger: "blur"}]
            },
            {type: 'select',label: '专区类型',
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=zone_type",
              span: 8, display: true, props: {label: "dictValue",value: "dictKey" },prop: 'zoneType',
              rules: [{ required: true, message: "请选择专区类型",trigger: "blur"}]
            },
            {type: 'input', label: '', span: 11,display: true,prop: 'a165750701340472520', labelWidth:1},
            {type: 'input', label: '', span: 12,display: true,prop: 'a165750701570373941', labelWidth:1}
          ],
          submitBtn: false,
          emptyBtn: false,
          menuSpan: 1,
          labelPosition: 'left',
        },
      }
    },
    created() {
      this.init()
    },
    mounted() {
      this.$nextTick(() => {
        this.bodyWidth = this.$refs.choiceB.offsetWidth -20;
      });
    },
    methods: {
      init() {
        getActivityLists().then(res => {
          this.activityList = res.data.data;
        });
      },
      checkChange(val, id) {
        if(val) {
          this.selectGood.push(id);
        }
        else {
          let index = this.selectGood.findIndex(ele => ele == id);
          if(index >= 0) this.selectGood.splice(index, 1);
        }
      },
      importSubmit() {
        this.$refs.importForm.validate((valid, done, msg) => {
          if(!valid) return;
          if(this.selectGood.length < 1) return this.$message.warning("您尚未勾选商品");
          const loading = this.$loading({
            lock: true,
            text: '导入中，请稍等...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          importGoods(this.selectGood.join(','), this.importForm.grossRate, this.importForm.categoryIds.join('-'), this.importForm.zoneType).then(res => {
            done();
            loading.close();
            this.selectGood = [];
            this.$refs.importForm.resetForm();
            this.$message({type: "success", message: "操作成功!"});
          })
          .catch(err => {
            done();
            loading.close();
            this.$message({type: "error", message: err.msg || err.message ||"操作失败!"});
          });
        })
      },
      changeData(form) {
        let data = JSON.parse(JSON.stringify(form));
        for (let k in data) {
          if(k.startsWith('$')) delete data[k];
          else {
            if(this.$refs[k + 'FormItem']) {
              let obj = this.$refs[k + 'FormItem'].getParam();
              data[k] = obj.show ? obj.value : `${obj.val1}-${obj.val2}`;
            }
            if(!data[k]) data[k] = undefined;
            else if(typeof data[k] == 'string' && data[k].includes('-')){
              let val = data[k].split('-');
              data[k] = { from: val[0], to: val[1]};
            }
            else if(Array.isArray(data[k])) data[k] = data[k][data[k].length - 1];
          }
        }
        return data;
      },
      submit(form, done) {
        this.loading = true;
        getList(this.changeData(form)).then(res => {
           let param = res.data.data;
           this.goodList = param.records;
           this.total = param.total;
           this.loading = false;
           done();
        })
        .catch(err => {
          console.log(err);
          this.loading = false;
          done();
        });
      },
      loadinit(parentId, resolve) {
        getByParentId({source: this.form.source, parentId}).then(res => {
          resolve(res.data.data);
        });
      },
      sourceChange(val) {
        getByParentId({source: val, parentId: 0}).then(res => {
          this.$refs.avueForm.updateDic('category_id', res.data.data);
        });
      },
      sizeChange(pageSize){
        this.form.limit = pageSize;
        this.submit(this.form, () => {});
      },
      currentChange(currentPage){
        this.form.page = currentPage;
        this.submit(this.form, () => {});
      },
    }
  }
</script>

<style scoped lang="scss">
  .good-li {
    display: flex;
    flex-wrap: wrap;
    .goods-item {
      margin-right: 20px;
    }
  }
  .choice-b {
    position: relative;
    width: 100%;
    .operation {
      position: fixed;
      bottom: 0px;
      .basic-container {
        padding: 0;
        margin: 0;
      }
      .paging {
        display: flex;
        align-items: center;
        justify-content: flex-end;
      }
    }
  }

</style>
