<template>
  <div style="width:804px">
    <div v-if="!showAddGiftMsg">
      <Row style="display: flex; justify-content: space-around">
        <Col span="8" >
        <div style="display: flex;align-items: center;margin-bottom: 16px;">
          <label style="width: 145px;">商品SKU/商品名</label>
          <Select
            v-model="formValidate3.SKU"
            filterable
            clearable
            @on-query-change="selectGiftGoods"
            @on-enter="searchSKU"
          >
            <Option
              v-for="(option,index) in modifyGoodsArr"
              :key="index"
              :value="option.value"
              :label="option.label"
            >
              {{ option.label }}
            </Option>
          </Select>
        </div>
        </Col>
        <Col span="8" >
        <div style="display: flex;align-items: center;margin-bottom: 16px;">
          <label style="width: 50px;">数量</label>
          <Input
            v-model="formValidate3.NUM"
            clearable
            @on-keyup="checkNum"
            @on-enter="searchSKU"
            :regx="regx"
          ></Input>
        </div>
        </Col>
        <Col span="2" >
        <Button
          type="primary"
          icon="md-return-left"
          @click="searchSKUBtn"
        >
          添加
        </Button>
        </Col>
      </Row>
      <!-- </Form> -->
      <Table
        border
        height="150"
        :columns="columns2"
        :data="giftTableDataAdd"
        size="large"
      />
      <footer style="display: flex; justify-content: flex-end; margin-top: 16px">
        <Button
          type="fcdefault"
          style="width: 80px; height: 34px; font-size: 14px"
          @click="cancelModal"
        >
          取消
        </Button>
        <Button
          type="posdefault"
          style="width: 80px; height: 34px; font-size: 14px; margin-left: 8px"
          @click="okAddGift"
        >
          确定
        </Button>
      </footer>
    </div>
    <div v-else>
        <p
            style="line-height: 16px;"
            v-html="massage"
        />
        <div style="display:flex;justify-content: flex-end;margin-top: 16px">
            <Button
              type="fcdefault"
              style="width: 80px; height: 34px; font-size: 14px"
              @click="cancelModal"
            >
            确定
            </Button>
        </div>

    </div>

  </div>
</template>
<script>
  const R3 = window.R3;
  const { network, urlSearchParams, store } = R3;
  export default {
    data() {
      return {
        regx: /^(([1-9][0-9]{0,4})|0|100000)$/, // 正整数0-100000
        showAddGiftMsg: false, // 调用添加赠品返回信息
        massage:'',
        idarray: [],
        formValidate3: {
          SKU: '',
          NUM: 1,
        },
        SKUData: [], // 表格数据
        modifyGoodsArr: [], // sku联想数据
        giftTableDataAdd: [],
        // 添加赠品数据
        columns2: [
          {
            type: 'index',
            title: '序号',
            align: 'center',
          },
          {
            title: '商品SKU',
            key: 'SKU',
            align: 'center',
          },
          {
            title: '商品编码',
            key: 'PRODUCTCODE',
            align: 'center',
          },
          {
            title: '数量',
            key: 'NUM',
            align: 'center',
          },
          {
            title: '商品名称',
            key: 'TITLE',
            align: 'center',
          },
          {
            title: '规格',
            key: 'NORMSDETAILNAMES',
            align: 'center',
          },
          {
            title: '国标码',
            key: 'GBCODE',
            align: 'center',
          },
          {
            title: '是否赠品',
            key: 'ISGIFT',
            align: 'center',
          },
          {
            title: '操作',
            key: 'action',
            width: 100,
            align: 'center',
            render: (h, params) => {
              const vm = this;
              return h('div', [
                h('Button', {
                  props: {
                    type: 'error',
                  },
                  on: {
                    click: () => {
                      vm.giftTableDataAdd.splice(params.index, 1);
                    }
                  }
                }, '删除')
              ]);
            }
          }
        ],
      };
    },
    created() {
      let modelName = R3.getModuleName();
      this.idarray = this.$store.state[modelName].buttons.selectIdArr;
      console.log(this.idarray, 888);
      this.getGiftList()
    },
    methods: {
      // 添加赠品按钮
      getGiftList() {
        let virtual = {
          table: 'V_IES_IESSKU',
          isdroplistsearch: false,
          range: 1000,
          startindex: 0,
          fixedcolumns: { ISGROUP: ['<>1'] }, //ISGIFT: ['=1'],
        };
        network.post('/p/cs/list/query', virtual).then((res) => {
          let data = [];
          for (let i = 0; i < res.data.rows.length; i++) {
            for (let j = 0; j < Object.keys(res.data.rows[i]).length; j++) {
              let keyName = Object.keys(res.data.rows[i])[j];
              res.data.rows[i][keyName] = res.data.rows[i][keyName].val;
            }
            data.push(res.data.rows[i]);
          }
          this.SKUData = data;
          this.modifyGoodsArr = this.SKUData.map((item) => ({
            value: item.SKU,
            label: `${item.SKU} ${item.TITLE || '  '} ${item.NORMS1NAME || '  '} ${item.NORMS1CODE || '  '} ${item.NORMS2NAME || '  '} ${item.NORMS2CODE || '  '}`,
          }));
        });
      },
      selectGiftGoods(query) {
        let index = query.indexOf(' ');
        let queryOne = -1
        if(index > 0){
          queryOne = query.substring(0,query.indexOf(' '));
        }else {
          queryOne = query
        }
        let params = {
            "page": 1,
            "pageSize": 1000,
            "searchVal": queryOne, //搜索内容(sku或skpu名称)
            // "isgift": '1',
            "isgroup": '0',
          }
          network.post('/p/cs/search/sku/str', params).then((res) => {
            this.SKUData = res.data.data.resultList.map((item) => ({
              SKU: item.SKU,
              PRODUCTCODE: item.PRODUCTCODE,
              TITLE: item.TITLE,
              GBCODE: item.GBCODE,
              NORMSDETAILNAMES: item.NORMSDETAILNAMES,
              ISGIFT: item.ISGIFT,
              SYSSTANDARDPRICE:item.SELLPRICE, //添加赠品标准金额字段
              NORMS1NAME: item.NORMS1NAME,
              NORMS1CODE: item.NORMS1CODE,
              NORMS2NAME: item.NORMS2NAME,
              NORMS2CODE: item.NORMS2CODE,
              // PLATSALEPRICE:item.SELLPRICE.val,//添加赠品平台销售价字段
            }));

            this.modifyGoodsArr = this.SKUData.map((item) => ({
              value: item.SKU,
              label: `${item.SKU} ${item.TITLE || '  '} ${item.NORMS1NAME || '  '} ${item.NORMS1CODE || '  '} ${item.NORMS2NAME || '  '} ${item.NORMS2CODE || '  '}`,
            }));
          });
        // let virtual = {
        //   table: 'V_IES_IESSKU',
        //   isdroplistsearch: true,
        //   range: 1000,
        //   startindex: 0,
        //   fixedcolumns: { ISGIFT: ['=1'], ISGROUP: ['<>1'], SKU: query },
        // };
        // network.post('/p/cs/list/query', virtual).then((res) => {
        //   this.SKUData = res.data.rows.map((item) => ({
        //     SKU: item.SKU.val,
        //     PRODUCTCODE: item.PRODUCTCODE.val,
        //     TITLE: item.TITLE.val,
        //     GBCODE: item.GBCODE.val,
        //     NORMSDETAILNAMES: item.NORMSDETAILNAMES.val,
        //     ISGIFT: item.ISGIFT.val,
        //     SYSSTANDARDPRICE: item.SELLPRICE.val, // 添加赠品标准金额字段
        //     // PLATSALEPRICE:item.SELLPRICE.val,//添加赠品平台销售价字段
        //   }));

        //   this.modifyGoodsArr = this.SKUData.map((item) => ({
        //     value: item.SKU,
        //     label: `${item.SKU} ${item.TITLE}`,
        //   }));
        // });
      },
      // 添加赠品数量校验只能为正整数
      checkNum() {
        let val = this.formValidate3.NUM;
        if (val) {
          if (!/(^[1-9]\d*$)/.test(val)) {
            this.$Message.warning('仅可输入正整数');
          }
        }
      },
      // 添加赠品搜索SKU按钮
      searchSKUBtn() {
        let that = this;
        if (!that.formValidate3.NUM) {
          that.$Message.warning('请输入数量');
          return;
        }
        let arr = this.SKUData.find(
          (item) => item.SKU == that.formValidate3.SKU
        );
        if (arr) {
          arr.NUM = that.formValidate3.NUM;
          let canSelect = false;
          //  有匹配到的数据
          that.giftTableDataAdd.forEach((item) => {
            if (item.SKU == arr.SKU) {
              //  表格中已经有数据，只要数量变
              item.NUM = item.NUM * 1 + arr.NUM * 1;
              canSelect = true;
            }
          });
          if (!canSelect) {
            //  表格中没有该数据，直接添加
            that.giftTableDataAdd.push(JSON.parse(JSON.stringify(arr)));
          }
        } else {
          this.$Message.error('不存在该商品');
        }
      },
      // 添加赠品搜索SKU
      searchSKU(e) {
        if (e.keyCode == 13) {
          let that = this;
          if (!that.formValidate3.NUM) {
            that.$Message.warning('请输入数量');
            return;
          }
          let arr = this.SKUData.find(
            (item) => item.SKU == that.formValidate3.SKU
          );
          if (arr) {
            arr.NUM = that.formValidate3.NUM;
            let canSelect = false;
            //  有匹配到的数据
            that.giftTableDataAdd.forEach((item) => {
              if (item.SKU == arr.SKU) {
                //  表格中已经有数据，只要数量变
                item.NUM = item.NUM * 1 + arr.NUM * 1;
                canSelect = true;
              }
            });
            if (!canSelect) {
              //  表格中没有该数据，直接添加
              that.giftTableDataAdd.push(JSON.parse(JSON.stringify(arr)));
            }
          } else {
            this.$Message.error('不存在该商品');
          }
        }
      },
      //   取消按钮
      cancelModal() {
        this.$emit('closeActionDialog', true);
      },
      // 确定添加赠品
      okAddGift() {
          console.log(this.giftTableDataAdd)
          let param=this.giftTableDataAdd.map((item)=>{
              return {
                  SKUS:item.SKU,
                  NUM:+item.NUM,
              }
          })
        let virtual={
            actionName: "T_V_OMSONLINEORDER_确认批量添加赠品",
            ids:this.idarray,
            isContainsParam: true,
            param: {param},
            tableName: "T_V_OMSONLINEORDER",
        }
        console.log(virtual,7878)
        network.post('/p/cs/exeAction',virtual).then((res) => {
            console.log(res.data.code)
            if(res.data.code==0){
              this.showAddGiftMsg=true
              this.massage=res.data.message
            }else{
              this.$emit('closeActionDialog', true);
            }
        })
      }
    }
  };
</script>
<style lang="less" scoped>

</style>
