<template>
  <CommonModal
    v-model="show"
    class="addGoodSkuModal"
    title="添加商品"
    width="1200"
    closable
    :on-confirm="onConfirm"
    @change="onVisibleChange"
    @keydown.native="onKeydown"
  >
    <div class="modal-content">
      <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px">
        <div style="display: flex; align-items: center">
          <label style="width: 120px">sku/商品名/国际码</label>
          <div
            class="SKUgoods"
            style="width: 180px; margin-left: 8px"
          >
            <Select
              ref="select"
              filterable
              clearable
              @on-query-change="selectSkuGoods"
              @on-change="onSelectChange"
            >
              <Option
                v-for="(option, index) in skuList"
                :key="index"
                :value="option.value"
                :label="option.label"
              >
                {{ option.label }}
              </Option>
            </Select>
          </div>
        </div>
        <div style="display: flex; align-items: center; margin-left: 10px">
          <label style="width: 30px">数量</label>
          <div
            class="SKUgoods"
            style="width: 120px; margin-left: 8px"
          >
            <Input
              v-model="formData.NUM"
              :regx="regx"
              clearable
            /></Input>
          </div>
        </div>
        <div style="display: flex; align-items: center; margin-left: 10px">
          <label style="width: 50px">成交金额</label>
          <div
            class="SKUgoods"
            style="width: 120px; margin-left: 8px"
          >
            <Input
              v-model="formData.ACTUALAMOUNT"
              :regx="regx1"
              clearable
            /></Input>
          </div>
        </div>

        <div style="display: flex; align-items: center; margin-left: 10px">
          <Button
            type="primary"
            icon="md-return-left"
            @click="add"
          >
            添加
          </Button>
        </div>
      </div>

      <Table
        border
        height="300"
        :columns="columns"
        :data="tableData"
        size="large"
      />
    </div>
  </CommonModal>
</template>

<script>
  import CommonModal from '../commonModal/index.vue';

  const R3 = window.R3;
  const { network } = R3;

  export default {
    name: 'addGoodSku',

    data() {
      return {
        show: this.visible,
        formData: {
          SKU: '',
          NUM: '',
          ACTUALAMOUNT: '',
        },
        regx: /^(([1-9][0-9]{0,4})|0|100000)$/, // 正整数0-100000
        regx1: /^\d{0,15}(\.[0-9]{0,4})?$/, // 四位小数的正数
        skuList: [], // 完整的商品列表
        columns: [
          {
            type: 'index',
            title: '序号',
            align: 'left',
            width: 50,
          },
          {
            title: '商品SKU',
            key: 'SKU',
            align: 'left',
            width: 120,
            tooltip: true,
          },
          {
            title: '商品编码',
            align: 'left',
            key: 'PRODUCTCODE'
          },
          {
            title: '商品名称',
            key: 'TITLE',
            width: 100,
            tooltip: true,
            align: 'left',
          },
          {
            title: '规格',
            align: 'left',
            key: 'SKUSPEC'
          },
          {
            title: '成本价',
            key: 'BASEPRICE',
            align: 'left',
          },
          {
            title: '销售价',
            key: 'SELLPRICE',
            align: 'left',
          },
          {
            title: '国际码',
            align: 'left',
            key: 'GBCODE'
          },
          {
            title: '数量',
            key: 'NUM',
            align: 'left',
            render: (h, params) => h(
              'Input',
              {
                style: {
                  width: '80px'
                },
                props: {
                  value: params.row.NUM,
                  regx: this.regx
                },
                on: {
                  'on-blur': (event) => {
                    if (isNaN(event.target.value)) {
                      event.target.value = '';
                    } else if (isNaN(event.target.value)) {
                      event.target.value = '';
                    } else {
                      this.tableData[params.index].NUM = event.target.value;
                    }
                  }
                }
              },
            ),
          },
          {
            title: '成交金额',
            key: 'ACTUALAMOUNT',
            align: 'left',
            render: (h, params) => h(
              'Input',
              {
                style: {
                  width: '80px'
                },
                props: {
                  value: params.row.ACTUALAMOUNT,
                  regx: this.regx1
                },
                on: {
                  'on-blur': (event) => {
                    if (isNaN(event.target.value)) {
                      event.target.value = '';
                    } else if (isNaN(event.target.value)) {
                      event.target.value = '';
                    } else {
                      this.tableData[params.index].ACTUALAMOUNT = event.target.value;
                    }
                  }
                }
              },
            ),
          },
          {
            title: '店铺可用库存',
            key: 'SHOPQTY',
            width: 86,
            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.tableData.splice(params.index, 1);
                    }
                  }
                }, '删除')
              ]);
            }
          }
        ],
        tableData: []
      };
    },

    model: {
      prop: 'visible',
      event: 'change',
    },

    props: {
      visible: {
        type: Boolean,
      },
      objId: {
        type: String,
      },
      orderStatus: {
        type: [Number, String],
      },
      ORDERSHOPID: {
        type: [Number, String],
      }
    },

    components: {
      CommonModal,
    },

    watch: {
      visible(val) {
        this.show = val;
        if (!val) {
          this.tableData = [];
          this.skuList = [];
          // 关闭弹框清空数据
          this.formData = {
            SKU: '',
            NUM: '',
            ACTUALAMOUNT: '',
          };
          // 请求接口方便下次打开弹框用
          this.getGoodsData();
        }
      },
    },

    mounted() {
      this.getGoodsData();
    },

    methods: {
      // 监听回车
      onKeydown(e) {
        if (e.keyCode == 13) {
          this.add();
        }
      },

      // 获取下拉框数据
      getGoodsData() {
        const params = {
          table: 'V_IES_IESSKU',
          isdroplistsearch: true,
          range: 500,
          startindex: 0,
          fixedcolumns: { ISPRESALE: ['<>1'], ISGROUP: ['<>1'] },
        };
        network.post(`/p/cs/list/query?hash=${+new Date()}`, params).then((res) => {
          this.skuList = res.data.rows.map((item) => ({
            ID: item.ID.val,
            SKU: item.SKU.val,
            PRODUCTCODE: item.PRODUCTCODE.val,
            TITLE: item.TITLE.val,
            SKUSPEC: item.NORMSDETAILIDS.val,
            BASEPRICE: item.BASEPRICE.val,
            SELLPRICE: item.SELLPRICE.val,
            GBCODE: item.GBCODE.val,
            ISGIFT: item.ISGIFT.val,
            value: item.SKU.val,
            label: `${item.SKU.val || '  '} ${item.TITLE.val || '  '} ${item.GBCODE.val || '  '} ${item.NORMS1NAME.val || '  '} ${item.NORMS1CODE.val || '  '} ${item.NORMS2NAME.val || '  '} ${item.NORMS2CODE.val || '  '}`,
          }));
        });
      },

      onVisibleChange(val) {
        this.$emit('change', val);
      },

      onConfirm() {
        if (!this.tableData.length) {
          this.$Message.error('请添加商品SKU');
          return;
        }
        const skus = this.tableData.map((item) => ({
          SKU: item.SKU || '',
          PRODUCTCODE: item.PRODUCTCODE || '',
          TITLE: item.TITLE || '',
          SKUSPEC: item.SKUSPEC || '',
          BASEPRICE: item.BASEPRICE || 0,
          GBCODE: item.GBCODE || '',
          ISGIFT: item.ISGIFT || '',
          SELLPRICE: item.SELLPRICE || 0,
          NUM: Number(item.NUM) || 0,
          ACTUALAMOUNT: Number(item.ACTUALAMOUNT) || 0
        }));
        const params = {
          objid: Number(this.objId),
          T_OMSONLINEORDERPRODUCT: skus
        };

        network.post('/p/cs/order/addDetails', params).then(res => {
          if (res.data.code == 0) {
            this.$Message.success(res.data.message);
            this.$emit('change', false);
            if (this.orderStatus === 4) {
              this.jumpNewOrder(res.data.data.objId);
            } else {
              this.$emit('on-confirm');
            }
          }
        });
      },

      // 跳转新订单
      jumpNewOrder(id) {
        const { fullPath } = this.$route;
        const {
          keepAliveModuleName,
          tableName,
        } = this.$store.state.global.activeTab;
        this.$store.commit('global/tabCloseAppoint', {
          tableName,
          routeFullPath: fullPath,
          keepAliveModuleName,
        });
        // 跳转
        R3.store.commit('global/tabOpen', {
          type: 'tableDetailAction' || 'C',
          label: '订单编辑',
          customizedModuleName: 'OrderManagementEditor',
          customizedModuleId: id,
        });
      },

      selectSkuGoods(query) {
        // if (value) {}
        let index = query.indexOf(' ');
        let queryOne = -1;
        if (index > 0) {
          queryOne = query.substring(0, query.indexOf(' '));
        } else {
          queryOne = query;
        }
        this.skuList = [];
        const params = {
          page: 1,
          pageSize: 10,
          searchVal: queryOne, // 搜索内容(sku或skpu名称)
          ispresale: '0',
          isgroup: '0',
          // iesShopId: this.ORDERSHOPID
        };
        network.post('/p/cs/search/sku/str', params).then((res) => {
          this.skuList = res.data.data.resultList.map((item) => ({
            ID: item.ID,
            SKU: item.SKU,
            PRODUCTCODE: item.PRODUCTCODE,
            TITLE: item.TITLE,
            SKUSPEC: item.NORMSDETAILIDS,
            BASEPRICE: item.BASEPRICE,
            GBCODE: item.GBCODE,
            ISGIFT: item.ISGIFT,
            SELLPRICE: item.SELLPRICE, // 添加赠品标准金额字段
            value: item.SKU,
            // SHOPQTY: this.skuList.SHOPQTY?this.skuList.SHOPQTY:0,
            label: `${item.SKU || '  '} ${item.TITLE || '  '} ${item.GBCODE || '  '} ${item.NORMS1NAME || '  '} ${item.NORMS1CODE || '  '} ${item.NORMS2NAME || '  '} ${item.NORMS2CODE || '  '}`,
          }));
        });
      },

      onSelectChange(value) {
        console.log(666,value)
        if(value){
          let param = {
            "iesShopId": this.ORDERSHOPID,
            "searchVal": value
          }
          network.post('/p/cs/search/sku/shopQty', param).then((res) => {
            this.currentSku.SHOPQTY = res.data.data.SHOPQTY
          })
        }
        this.currentSku = this.skuList.find(
          (item) => item.SKU == value
        );
        console.log(123,this.currentSku)
      },

      add() {
        const skuData = this.currentSku;
        if (skuData) {
          let canSelect = false;
          //  有匹配到的数据
          this.tableData.forEach((item) => {
            if (item.SKU == skuData.SKU) {
              //  表格中已经有数据，只要数量变
              canSelect = true;
            }
          });
          if (!canSelect) {
            //  表格中没有该数据，直接添加
            skuData.NUM = this.formData.NUM;
            skuData.ACTUALAMOUNT = this.formData.ACTUALAMOUNT;
            this.tableData.push(JSON.parse(JSON.stringify(skuData)));

            // 清除输入框
            this.formData.NUM = '';
            this.formData.ACTUALAMOUNT = '';
            this.$refs.select.clearSingleSelect();
          } else {
            this.$Message.error('该商品已存在');
          }
        } else {
          this.$Message.error('不存在该商品');
        }
      },
    },
  };
</script>

<style lang="less">
.addGoodSkuModal {
  .ark-btn {
    height: 34px;
    font-size: 14px;
  }
}
</style>

<style scoped lang="less"></style>
