<template>
  <div>
    <div v-if="!isSuccess">
      <p
        v-if="operation"
        class="modal-text"
      >
        已勾选配货单数据存在不是未确认状态，不能进行此操作！
      </p>
      <businessForm
        v-else
        :form-config="formConfig"
      />
      <Form
        v-if="isAirEmbargoFormItemShow && !operation"
        :label-width="120"
      >
        <FormItem label="是否航空禁运:">
          <RadioGroup v-model="is_air_embargo">
            <Radio label="1">
              是
            </Radio>
            <Radio label="0">
              否
            </Radio>
          </RadioGroup>
        </FormItem>
      </Form>
      <businessButton :btn-config="btnConfig" />
    </div>
    <div v-else>
      <p
        style="line-height: 16px;"
        v-html="SuccessMsg"
      />
      <div
        class="pop-btn"
        style="display:flex;justify-content: flex-end;"
      >
        <Button
          type="fcdefault"
          class="sav-btn"
          @click="close"
        >
          确定
        </Button>
      </div>
    </div>
  </div>
</template>


<script lang="js">
  import common from '@yunque/service/modules/common';
  import businessForm from 'professionalComponents/businessForm';
  import businessButton from 'professionalComponents/businessButton';
  // import R3 from '../../../static/r3/r3.publish/r3.min';
  const R3 = window.R3;
  export default {
    name: 'GenerateWarehouseReceiptModal',
    props: {
      idArray: { // 获取ID用于多选
        type: [Array, Object],
        default: () => {}
      },
      itemId: {// 获取当前子表表名
        type: String,
        default: () => ''
      },
      selectRowData: { // 获取选择行的数据
        type: Array,
        default: () => []
      }
    },
    components: {
      businessForm,
      businessButton
    },
    data() {
      return {
        isSuccess: false, // 调接口成功
        SuccessMsg: '', // 成功返回的信息
        sellerNick: '', // 点击确认传店铺表卖家昵称
        isAirEmbargoFormItemShow: false,
        is_air_embargo: '0',
        operation: false, // 是否可以操作
        formConfig: {
          formValue: {
            carrier_code: '', // 承运商
            status: 'a', // 商品状态
          },
          formData: [
            {
              style: 'select',
              label: '承运商',
              value: 'carrier_code', // 输入框的值
              width: '24',
              multiple: false, // 布尔值,下拉框是否开启多选,默认为不开启
              disabled: false, // 是否禁用,默认为false
              clearable: true, // 下拉选中是否显示清空按钮,默认为false
              clearSelect: () => {
              }, // 点击清空按钮回调
              selectChange: () => {
                if (this.formConfig.formValue.carrier_code === '120001552') {
                  this.isAirEmbargoFormItemShow = true;
                } else {
                  this.isAirEmbargoFormItemShow = false;
                }
              }, // 选中事件，默认返回选中的值,默认返回当前值value
              setRequired: 'required', // 必选标识,值不为required时无标识
              options: [
                {
                  value: '120001552', 
                  label: '唯品专配' 
                },
                {
                  value: '0',
                  label: '店铺所属承运商'
                }]
            }
          ]
        },
        btnConfig: {
          typeAll: 'error', // 按钮统一风格样式
          btnsite: 'right', // 按钮位置 (right , center , left)
          buttons: [
            {
              type: '', // 按钮类型
              text: '取消', // 取消 按钮文本
              icon: '', // 按钮图标
              size: '', // 按钮大小
              disabled: false, // 按钮禁用控制
              btnclick: () => {
                this.$emit('closeActionDialog', true);
              } // 按钮点击事件
            },
            {
              type: '', // 按钮类型
              text: '确定', // 按钮文本
              icon: '', // 按钮图标
              size: '', // 按钮大小
              class: '', // 加载中样式
              loading: false, // 加载中
              disabled: false, // 按钮禁用控制
              btnclick: () => {
                this.determine();
              }, // 按钮点击事件
            }
          ]
        },
      };
    },

    async created() {
      // 判断勾选的数据是否有不是未确认状态
      await this.selectRowData.forEach((element) => {
        if (element.VIRSTATUS.val !== '未确认') {
          this.operation = true;
          this.btnConfig.buttons.splice(1);
        }
      });
      // 判断店铺、发货实体仓库、JIT仓库及配送方式是否一致
      const selectRowData = this.selectRowData[0];
      console.log(this.selectRowData, '选中的');
      console.log(this.idArray, '选中的');

      // const agreement = await this.selectRowData.every(item => item.ORDERSHOPID.refobjid === selectRowData.ORDERSHOPID.refobjid
      //   && item.IESWAREHOUSEID.refobjid === selectRowData.IESWAREHOUSEID.refobjid
      //   && item.DELIVERY_METHOD.val === selectRowData.DELIVERY_METHOD.val
      //   && item.JITWAREHOUSEID.refobjid === selectRowData.JITWAREHOUSEID.refobjid);
      // if (!agreement) {
      //   this.$emit('closeActionDialog', false);
      //   this.$Message.warning('请选择店铺、发货实体仓库、JIT仓库及配送方式一致的配货单');
      // }

      // 承运商写死了不用通过店铺id查询
      // if (!this.operation) {
      //   await this.getShopInfo();
      // }
    },
    mounted() {
      // 弹窗关闭时刷新页面
      document.getElementsByClassName('ark-modal-close')[0].addEventListener('click', () => {
        const { fullPath } = this.$route;
        let index = fullPath.lastIndexOf('/');
        let tableId = fullPath.slice(index + 1, fullPath.length);
        const {
          keepAliveModuleName, tableName
        } = this.$store.state.global.activeTab;
        this.$store.commit('global/tabCloseAppoint', {
          tableName,
          routeFullPath: fullPath,
          keepAliveModuleName,
        });
        // 跳转
        this.$store.commit('global/tabOpen', {
          type: 'S',
          tableName,
          tableId,
          back: true
        });
      });
    },
    methods: {
      close() {
        this.$emit('closeActionDialog', true); // true刷新
      },
      // 生成物流单号
      setLogisticNo() {
        //年月日时分秒+随机两位数
        var d = new Date();
        var year = d.getFullYear();
        var mon = d.getMonth() + 1;
        var day = d.getDate();
        var hh  = d.getHours();
        var mm  = d.getMinutes();
        var ss = d.getSeconds();
        let s = year+(mon<10?('0'+mon):mon)+(day<10?('0'+day):day)+(hh<10?('0'+hh):hh)+(mm<10?('0'+mm):mm)+(ss<10?('0'+ss):ss)+this.randomTwoDigits();;
        return s;
      },
      randomTwoDigits() {
        const min = 10;
        const max = 99;
        const randomNum = Math.floor(Math.random() * (max - min + 1)) + min;
        return randomNum.toString().padStart(2, '0');
      },
      // 确定
      async determine() {
        // 如果不是唯品专供 is_air_embargo 不传值（是否航空禁运）
        // 如果是唯品专供 carrier_code 承运商id传 120001552

        // ORDERSHOPID下单店铺，IESWAREHOUSEID发货实体仓库，DELIVERY_METHOD配送方式，JITWAREHOUSEID JIT仓库编码，DELIVERYHOURSENAME JIT仓库名称
        const params = this.selectRowData.map(item=>({
          ids: item.ID.val,
          // sellerNick: this.sellerNick,
          // deliveryMethod: item.DELIVERY_METHOD.val, // 配送方式
          // deliveryWarehouse: item.IESWAREHOUSEID.val, // 供应商发货仓库
          // warehouse: item.DELIVERYHOURSENAME.val, // JIT仓库
          isShopCarrierCode: this.formConfig.formValue.carrier_code == '120001552' ? 1 : 0, // 是否选择唯品专配承运商
          isAirEmbargo: this.formConfig.formValue.carrier_code == '120001552' ? this.is_air_embargo : '', // 是否航空禁运
          carrierCode: this.formConfig.formValue.carrier_code == '120001552' ? '120001552' : '', //  承运商id
          logisticsNo: this.formConfig.formValue.carrier_code == '120001552' ? '' : this.setLogisticNo() // 物流单号
        }));
        console.log(params, 9999);
        // const param = {
        //   ids: this.idArray.join(','), // 明细id
        //   // sellerNick: this.selectRowData[0].ORDERSHOPID.val,
        //   sellerNick: this.sellerNick,
        //   isAirEmbargo: this.formConfig.formValue.carrier_code == '120001552' ? this.is_air_embargo : '', // 是否航空禁运
        //   carrierCode: this.formConfig.formValue.carrier_code, //  承运商id
        //   logisticsNo: this.formConfig.formValue.carrier_code == '120001552' ? '' : '123456' // 物流单号
        // };
        this.btnConfig.buttons[1].class = 'loadingBtn';
        this.btnConfig.buttons[1].loading = true;
        const res = await this.service.storageContent.createPoDelivery(params);
        console.log(res);
        if (res.data.code === 0) {
          // this.$Message.success(res.data.message || '成功！');
          this.btnConfig.buttons[1].class = '';
          this.btnConfig.buttons[1].loading = false;
          
          this.isSuccess = true; // 调接口成功
          let msg = res.data.message;
          this.SuccessMsg = msg.replace(/\n/g, '<br/>');// 成功返回的信息
        } else {
          this.btnConfig.buttons[1].class = '';
          this.btnConfig.buttons[1].loading = false;
        }
      },
      /**
       * 获取店铺信息
       */
      async getShopInfo() {
        const rfShop = this.selectRowData[0].ORDERSHOPID;
        const shopModel = await common.objectQuery({
          objid: rfShop.refobjid,
          table: rfShop.reftablename
        });
        // 查询店铺的"单承运商编码和名称"
        if (shopModel) {
          console.log(shopModel.SELLERNICK);
          this.sellerNick = shopModel.SELLERNICK;
          const logisticsCompanyCode = shopModel.LOGISTICSCOMPNAYCODE;
          // 获取店铺的承运商追加到下拉选项中
          this.formConfig.formData[0].options.push({ value: logisticsCompanyCode, label: shopModel.LOGISTICSCOMPNAYNAME });
          // 判断承运商编码是否为120001552
          if (logisticsCompanyCode === '120001552') {
            this.formConfig.formData[0].disabled = true;
            this.formConfig.formData[0].selectChange = () => {};
            this.formConfig.formValue.carrier_code = logisticsCompanyCode;
          } else {
            this.formConfig.formData[0].options.push({ value: '120001552', label: '唯品专配' });
            this.formConfig.formValue.carrier_code = '120001552';
          }
        }
      }
    }
  };
</script>
