<template>
  <div class="goodChangeOne">
    <Spin fix v-if="loading">
          <div class="loader">
            <svg class="circular" viewBox="25 25 50 50">
              <circle class="path" cx="50" cy="50" r="20" fill="none" stroke-width="5" stroke-miterlimit="10"></circle>
            </svg>
          </div>
          <div>请稍后...</div>
        </Spin>
    <div class="topTips">
      操作后会将选中订单中包含的【原商品】替换为【新商品】，且重新释放占用库存。（暂不支持组合商品的sku替换）
    </div>
    <div class="content">
      <Form
        ref="formValidate"
        :model="formValidate"
        :rules="ruleCustom"
        label-position="left"
        :label-width="50"
      >
        <FormItem
          label="原商品"
          prop="originalSKU"
        >
          <Select
            v-model="formValidate.originalSKU"
            class="selectItem"
            filterable
            clearable
            style="width:300px"
            placeholder="请输入原商品sku"
            @on-query-change="selectOriginalSKU"
            @on-change="findOriginalGoods"
          >
            <Option
              v-for="(option,index) in originSKUList"
              :key="index"
              :value="option.value"
              :label="option.value"
            >
              {{ option.label }}
            </Option>
          </Select>
        </FormItem>
        <div
          v-if="originGood"
          class="detailContent"
        >
          <img
            style="width:60px;height:60px"
            :src="originGood.PICPATH==''?'../../../static/img/camera.jpg':originGood.PICPATH"
          >
          <div style="flex:1;line-height:18px;margin-left:16px">
            <div class="title">
              【{{ originGood.BRANDID }}】{{ originGood.TITLE }}
            </div>
            <div style="display:flex;justify-content: space-between;">
              <div><span style="color:#666666">商品编码：</span>{{ originGood.PRODUCTCODE }}</div>
              <div><span style="color:#666666">规格：</span>{{ originGood.NORMSDETAILNAMES }}</div>
              <div><span style="color:#666666">标准价：</span>{{ originGood.SYSSTANDARDPRICE }}元</div>
            </div>
          </div>
        </div>
        <FormItem
          label="新商品"
          prop="newSKU"
        >
          <Select
            v-model="formValidate.newSKU"
            class="selectItem"
            filterable
            clearable
            style="width:300px"
            placeholder="请输入新商品sku"
            @on-query-change="selectNewSKU"
            @on-change="findNewGoods"
          >
            <Option
              v-for="(option,index) in newSKUList"
              :key="index"
              :value="option.value"
              :label="option.value"
            >
              {{ option.label }}
            </Option>
          </Select>
        </FormItem>
        <div
          v-if="newGood"
          class="detailContent"
        >
          <img
            style="width:60px;height:60px"
            :src="newGood.PICPATH==''?'../../../static/img/camera.jpg':newGood.PICPATH"
          >
          <div style="flex:1;line-height:18px;margin-left:16px">
            <div class="title">
              【{{ newGood.BRANDID }}】{{ newGood.TITLE }}
            </div>
            <div style="display:flex;justify-content: space-between;">
              <div><span style="color:#666666">商品编码：</span>{{ newGood.PRODUCTCODE }}</div>
              <div><span style="color:#666666">规格：</span>{{ newGood.NORMSDETAILNAMES }}</div>
              <div><span style="color:#666666">标准价：</span>{{ newGood.SYSSTANDARDPRICE }}元</div>
            </div>
          </div>
        </div>
      </Form>
    </div>
    <div class="bottomBtnBox">
      <Button
        size="small"
        class="cancelBtn"
        type="fcdefault"
        @click="close"
      >
        取消
      </Button>
      <Button
        type="fcdefault"
        size="small"
        class="sureBtn"
        @click="sureAdd('formValidate')"
      >
        确定
      </Button>
    </div>
    <Modal
      v-model="errorModal"
      title="商品替换结果"
      :mask="mask"
      closable
      true
    >
      <div
        v-if="errorMsg.errorList.length>0"
        class="error-content"
      >
        <div class="error-message">
          <div class="left-icon">
            <i class="iconfont">&#xecd0;</i>
          </div>
          <div class="right-content">
            <div class="content-message">
              <p class="title">
                {{ errorMsg.message }}
              </p>
              <p
                v-for="(msg,index) in errorMsg.errorList"
                :key="index"
              >
                {{ msg.id }}：{{ msg.message }}
              </p>
            </div>
          </div>
        </div>
      </div>
    </Modal>
  </div>
</template>
<script>
  const R3 = window.R3;
  const { network, urlSearchParams, store } = R3;
  export default {
    props: {
      idArray: {// 可获取明细表勾选的明细ID
        type: [Array, Object],
        default: () => {}
      },
      selectRowData: {// 获取ID用于多选,获取勾选的明细对应的row内的数据
        type: [Array, Object],
        default: () => {}
      }
    },
    data() {
      const validateSKU = (rule, value, callback) => {
        if (!this.formValidate.originalSKU) {
          callback(new Error('请输入商品sku'));
        } else if (this.formValidate.newSKU == this.formValidate.originalSKU) {
          // callback(new Error('原商品和新商品不能相同'));
          // 对第二个密码框单独验证
          this.$refs.formValidate.validateField('newSKU');
          callback();
        } else {
          callback();
        }
      };
      const SKUCheck = (rule, value, callback) => {
        if (!this.formValidate.newSKU) {
          callback(new Error('请输入商品sku'));
        } else if (this.formValidate.newSKU == this.formValidate.originalSKU) {
          callback(new Error('原商品和新商品不能相同'));
        } else {
          callback();
        }
      };
      return {
        errorModal: false, // 替换失败
        errorMsg: {
          message: '',
          errorList: []
        },
        mask: 'true',
        formValidate: {
          originalSKU: '',
          newSKU: '', // 新SKU
        },
        originSKUList: [],
        originSKUData: [], // 原sku查到的所有商品信息
        originGood: '', // 原sku带出商品信息
        newSKUList: [],
        newSKUData: [], // 新sku带出商品信息
        newGood: '', // 新sku带出商品信息

        ruleCustom: {
          originalSKU: [
            { validator: validateSKU, trigger: 'change' }
          ],
          newSKU: [
            { validator: SKUCheck, trigger: 'change' }
          ],
        },
        loading: false,
      };
    },
    watch: {
      'formValidate.originalSKU': function (val) {
        console.log(val, 7777);
        this.$refs.formValidate.validate();
      },
      'formValidate.newSKU': function (val) {
        this.$refs.formValidate.validate();
      },
    },
    created() {
      // 初始化渲染下拉列表
      let virtual = {
        table: 'V_IES_IESSKU',
        isdroplistsearch: true,
        range: 200,
        startindex: 0,
        fixedcolumns: { ISGROUP: ['<>1'] },
      };
      network.post('/p/cs/list/query', virtual).then((res) => {
        this.newSKUData = res.data.rows.map((item) => ({
          SKU: item.SKU.val,
          BRANDID: item.BRANDID.val, // 品牌
          PRODUCTCODE: item.PRODUCTCODE.val, // 商品编码
          TITLE: item.TITLE.val,
          NORMSDETAILNAMES: item.NORMSDETAILNAMES.val, // 规格
          SYSSTANDARDPRICE: item.SELLPRICE.val, // 标准价
          PICPATH: item.PICTUREURL.val, // 图片
          NORMS1NAME: item.NORMS1NAME.val,
          NORMS1CODE: item.NORMS1CODE.val,
          NORMS2NAME: item.NORMS2NAME.val,
          NORMS2CODE: item.NORMS2CODE.val,
        }));
        let reg = /\\/g;
        this.newSKUData.forEach((item)=>{
          if (item.PICPATH && item.PICPATH[0] == '[') {
            item.PICPATH = JSON.parse(item.PICPATH.replace(reg, ''))[0].URL;
          }
        });
        this.newSKUList = this.newSKUData.map((item) => ({
          value: item.SKU,
          label: `${item.SKU} ${item.NORMS1NAME || '  '} ${item.NORMS1CODE || '  '} ${item.NORMS2NAME || '  '} ${item.NORMS2CODE || '  '}`,
        }));
      });

      let params = {
        ids: this.idArray
      }
      network.post('/p/cs/order/querySku',params).then(res => {
          this.originSKUData = res.data.data.map((item) => ({
            SKU: item.SKU,
            BRANDID: item.BRANDID, // 品牌
            PRODUCTCODE: item.PRODUCTCODE, // 商品编码
            TITLE: item.TITLE,
            NORMSDETAILNAMES: item.NORMSDETAILNAMES, // 规格
            SYSSTANDARDPRICE: item.SELLPRICE, // 标准价
            PICPATH: item.PICTUREURL, // 图片
            NORMS1NAME: item.NORMS1NAME,
            NORMS1CODE: item.NORMS1CODE,
            NORMS2NAME: item.NORMS2NAME,
            NORMS2CODE: item.NORMS2CODE,
          }));
          let reg = /\\/g;
          this.originSKUData.forEach((item)=>{
            if (item.PICPATH && item.PICPATH[0] == '[') {
              item.PICPATH = JSON.parse(item.PICPATH.replace(reg, ''))[0].URL;
            }
          });
          // this.newSKUData = this.originSKUData;
          this.originSKUList = this.originSKUData.map((item) => ({
            value: item.SKU,
            label: `${item.SKU} ${item.NORMS1NAME || '  '} ${item.NORMS1CODE || '  '} ${item.NORMS2NAME || '  '} ${item.NORMS2CODE || '  '}`,
          }));
          // this.newSKUList = this.originSKUList;
      })
    },
    methods: {
      // 模糊搜索
      selectOriginalSKU(query) {
        let virtual = {
          table: 'V_IES_IESSKU',
          isdroplistsearch: true,
          range: 200,
          startindex: 0,
          fixedcolumns: { SKU: query, ISGROUP: ['<>1'] },
        };
        network.post('/p/cs/list/query', virtual).then((res) => {
          console.log(res.data.rows);
          this.originSKUData = res.data.rows.map((item) => ({
            SKU: item.SKU.val,
            BRANDID: item.BRANDID.val, // 品牌
            PRODUCTCODE: item.PRODUCTCODE.val, // 商品编码
            TITLE: item.TITLE.val,
            NORMSDETAILNAMES: item.NORMSDETAILNAMES.val, // 规格
            SYSSTANDARDPRICE: item.SELLPRICE.val, // 标准价
            PICPATH: item.PICTUREURL.val, // 图片
            NORMS1NAME: item.NORMS1NAME.val,
            NORMS1CODE: item.NORMS1CODE.val,
            NORMS2NAME: item.NORMS2NAME.val,
            NORMS2CODE: item.NORMS2CODE.val,
          }));
          let reg = /\\/g;
          this.originSKUData.forEach((item)=>{
            if (item.PICPATH && item.PICPATH[0] == '[') {
              item.PICPATH = JSON.parse(item.PICPATH.replace(reg, ''))[0].URL;
            }
          });
          this.originSKUList = this.originSKUData.map((item) => ({
            value: item.SKU,
            label: `${item.SKU} ${item.NORMS1NAME || '  '} ${item.NORMS1CODE || '  '} ${item.NORMS2NAME || '  '} ${item.NORMS2CODE || '  '}`,
          }));
        });
      },
      //   选中下拉值
      findOriginalGoods(e) {
        this.originGood = this.originSKUData.find(
          (item) => item.SKU == this.formValidate.originalSKU
        );
        console.log('渲染信息', this.originGood);
      },
      //   模糊搜索
      selectNewSKU(query) {
        console.log(456, query);
        let virtual = {
          table: 'V_IES_IESSKU',
          isdroplistsearch: true,
          range: 200,
          startindex: 0,
          fixedcolumns: { SKU: query, ISGROUP: ['<>1'] },
        };
        network.post('/p/cs/list/query', virtual).then((res) => {
          console.log(res.data.rows);
          this.newSKUData = res.data.rows.map((item) => ({
            SKU: item.SKU.val,
            BRANDID: item.BRANDID.val, // 品牌
            PRODUCTCODE: item.PRODUCTCODE.val, // 商品编码
            TITLE: item.TITLE.val,
            NORMSDETAILNAMES: item.NORMSDETAILNAMES.val, // 规格
            SYSSTANDARDPRICE: item.SELLPRICE.val, // 标准价
            PICPATH: item.PICTUREURL.val, // 图片
            NORMS1NAME: item.NORMS1NAME.val,
            NORMS1CODE: item.NORMS1CODE.val,
            NORMS2NAME: item.NORMS2NAME.val,
            NORMS2CODE: item.NORMS2CODE.val,
          }));
          let reg = /\\/g;
          this.newSKUData.forEach((item)=>{
            if (item.PICPATH && item.PICPATH[0] == '[') {
              item.PICPATH = JSON.parse(item.PICPATH.replace(reg, ''))[0].URL;
            }
          });
          this.newSKUList = this.newSKUData.map((item) => ({
            value: item.SKU,
            label: `${item.SKU} ${item.NORMS1NAME || '  '} ${item.NORMS1CODE || '  '} ${item.NORMS2NAME || '  '} ${item.NORMS2CODE || '  '}`,
          }));
        });
      },
      //   选中下拉值
      findNewGoods(e) {
        this.newGood = this.newSKUData.find(
          (item) => item.SKU == this.formValidate.newSKU
        );
      },
      //   确定按钮
      sureAdd(name) {
        let cango = false;
        this.$refs[name].validate((valid) => {
          console.log(valid, 777);
          if (valid) {
            cango = true;
          }
        });
        setTimeout(()=>{
          if (cango) {
            if (this.originGood.SYSSTANDARDPRICE != this.newGood.SYSSTANDARDPRICE) {
              this.$Modal.fcWarning({
                title: '商品替换确认',
                content: '原商品和新商品系统标准价不一致，是否确定替换，如仍需替换，请点击确定。',
                mask: true,
                showCancel: true,
                loading: true,
                onOk: ()=>{
                  this.saveData();
                }
              });
            } else {
              this.$Modal.fcWarning({
                title: '商品替换确认',
                content: '是否确定要进行商品替换？',
                mask: true,
                showCancel: true,
                loading: true,
                onOk: ()=>{
                  this.saveData();
                }
              });
            }
          }
        }, 200);
      },
      close() {
        // 成功关闭弹框
        this.$emit('closeActionDialog', true);
      },
      saveData() {
        let modelName = R3.getModuleName();
        let idarray = this.$store.state[modelName].buttons.selectIdArr;
        let virtual = {
          orderIdList: idarray,
          originalProductCode: this.formValidate.originalSKU,
          currentProductCode: this.formValidate.newSKU,
        };
        this.loading = true;
        network.post('/p/cs/order/item/sku/replace', virtual).then((res) => {
          this.$Modal.remove();
          if (res.data.code == 0) {
            if (res.data.data.errors.length) {
              this.errorMsg.errorList = res.data.data.errors;
              this.errorMsg.message = res.data.message;
              this.errorModal = true;
              this.loading = false;
            } else {
              this.$Modal.fcSuccess({
                title: '商品替换结果',
                content: res.data.message,
                mask: true,
                closable: true
              });
              this.loading = false;
              this.$emit('closeActionDialog', true);
              document.querySelector('#refresh').click(); // 标准列表刷新按钮
            }
          }else {
            this.loading = false;
            this.$emit('closeActionDialog', true);
            document.querySelector('#search').click(); // 标准列表刷新按钮
          }
        });
      }
    }
  };
</script>
<style lang="less">

.topTips{
    padding: 8px;
    background-color: #D5E7FF;
    color: #0046B9;
    line-height: 17px;
}
.goodChangeOne .content{
    margin:16px;
    .ark-form-item{
        margin-bottom: 16px!important
    }
    .detailContent{
        display: flex;
        align-items: center;
        font-weight: 500;
        color: #000;
        margin-bottom:16px ;
    }
    .ark-select-single .ark-select-selection{
      height: 32px !important;
    }

}

.bottomBtnBox {
    width: calc(100% - 48px);
    margin: 16px auto 0px;
    text-align: center;
    .cancelBtn,.sureBtn {
      width: 72px;
      height: 32px;
      font-size: 12px;
    }
    .cancelBtn {
      margin-right: 8px;
    }
  }

  .error-content {
    text-align: left;
    position: relative;
    font-size: 12px;
    margin-top: 10px;
    .error-message {
      height: auto;
      margin: 10px 0px;
      max-height: 240px;
      position: relative;
      .left-icon {
        height: 28px;
        width: 28px;
        position: absolute;
        left: 0;
        top: 0;
        i {
          font-size: 28px;
          color: #e80000;
        }
      }
      .right-content {
        position: relative;
        margin-left: 38px;
        .link {
          line-height: 16px;
          a {
            color: #0f8ee9;
            cursor: pointer;
            display: inline-block;
            padding-top: 6px;
            text-decoration: none;
          }
        }
        .content-message {
          max-height: 220px;
          min-height: 28px;
          overflow: auto;
          p {
            word-break: break-word;
            line-height: 16px;
            margin: 6px 0;
          }
        }
      }
    }
  }
</style>
