<template>
  <div
    class="createDelivery" data-key="CREATE_WAREHOUSE_ORDER">
    <Form
      ref="formInline"
      :model="formInline"
      :rules="ruleInline"
      :label-width="110"
    >
      <FormItem label="店铺">
        <Select
          filterable
          label-in-value
          @on-change="changeStoreChoosed"
        >
          <Option
            v-for="item in storeList"
            :key="item.value"
            :value="item.value"
          >
            {{ item.label }}
          </Option>
        </Select>
      </FormItem>
      <FormItem
        ref="LOGISTICSCOMPNAYNAME"
        label="承运商"
        prop="LOGISTICSCOMPNAYNAME"
        class="LOGISTICSCOMPNAYNAME"
      >
        <Select
          v-model="formInline.LOGISTICSCOMPNAYChoosed"
          @on-change="changeLOGISTICSCOMPNAYChoosed"
        >
          <Option
            v-for="item in LOGISTICSCOMPNAYList"
            :key="item.value"
            :value="item.value"
          >
            {{ item.label }}
          </Option>
        </Select>
      </FormItem>
      <FormItem
        ref="isAirEmbargo"
        class="isAirEmbargo"
        label="是否航空禁运"
      >
        <RadioGroup v-model="formInline.is_air_embargo">
          <Radio label="否" />
          <Radio label="是" />
        </RadioGroup>
      </FormItem>
      <FormItem
        ref="warehouseChoosed"
        class="warehouseChoosed"
        label="发货实体仓库"
      >
        <Select
          ref="selectWarehouse"
          clearable
          @on-change="changewarehouseChoosed"
        >
          <Option
            v-for="item in warehouseList"
            :key="item.value"
            :value="item.value"
          >
            {{ item.label }}
          </Option>
        </Select>
      </FormItem>
    </Form>
    <div class="bottomBtnBox">
      <Button
        size="small"
        class="cancelBtn"
        ghost
        @click="cancel"
      >
        取消
      </Button>
      <Button
        :loading="loading"
        type="primary"
        size="small"
        class="sureBtn"
        @click="createDelivery"
      >
        保存
      </Button>
    </div>
  </div>
</template>


<script>
  const R3 = window.R3;

  const { network } = R3;
  export default {
    props: {
      selectRowData: {// 获取ID用于多选,获取勾选的明细对应的row内的数据
        type: [Array, Object],
        default: () => {}
      }
    },
    data() {
      return {
        formInline: {
          storeChoosed: '',
          storeChoosedName: '',
          LOGISTICSCOMPNAYChoosed: '',
          is_air_embargo: '否',
          warehouseChoosed: '',
          warehouseChoosedId: '',
        },
        ruleInline: {
          LOGISTICSCOMPNAYNAME: [
            { required: true, message: '请选择承运商', trigger: 'blur' }
          ],
        },
        storeListAll: [], // 店铺列表原始数据
        storeList: [], // 店铺列表
        LOGISTICSCOMPNAYList: [
          {
            label: '唯品专配',
            value: '120001552'
          }
        ], // 承运商列表
        warehouseListAll: [], // 发货实体仓库原始数据
        warehouseList: [], // 发货实体仓库
        LOGISTICSShow: true,
        isChoosedStore: true,
        loading: false,
      };
    },
    created() {
      this.getStoreList();
    },
    methods: {
      // 生成物流单号
      setLogisticNo() {
        //年月日时分秒+随机两位数
        let d = new Date();
        let year = d.getFullYear();
        let mon = d.getMonth() + 1;
        let day = d.getDate();
        let hh = d.getHours();
        let mm = d.getMinutes();
        let 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');
      },
      getStoreList() {
        let params = {
          table: 't_iesshop',
          isdroplistsearch: true,
          range: 1000,
          startindex: 0,
          fkdrplist: { searchcols: ['SHOPTITLE', 'ID', 'LOGISTICSCOMPNAYCODE', 'LOGISTICSCOMPNAYNAME', 'STOREIDS'] },
          fixedcolumns: { PLATFORM: '=19', ISACTIVE: 'Y' }
        };
        network.post('/p/cs/list/query', params).then(res => {
          console.log('生成出仓单', res);
          // if (res.status == 200 && res.statusText == 'OK') {
          this.storeListAll = res.data.rows;
          res.data.rows.forEach(item => {
            let obj = {
              label: item.SHOPTITLE.val,
              value: item.ID.val,
            };
            this.storeList.push(obj);
          });
          console.log('生成出仓单11', this.storeList);
          // }
        });
      },
      getWarehouseList(id) {
        let params = {
          table: 'T_IESSTORE',
          isdroplistsearch: true,
          range: 1000,
          startindex: 0,
          fixedcolumns: { ID: id }
        };
        network.post('/p/cs/list/query', params).then(res=> {
          let warehouseIds = '';
          if (res.data.rows && res.data.rows.length > 0) {
            res.data.rows.forEach((item, index) => {
              if (index == res.data.rows.length - 1) {
                warehouseIds += item.IESWAREHOUSEID.refobjid; 
              } else {
                warehouseIds += `${item.IESWAREHOUSEID.refobjid},`;
              }
            });
          }
          let params = {
            table: 'T_IESWAREHOUSE',
            isdroplistsearch: true,
            range: 1000,
            startindex: 0,
            fixedcolumns: { ISACTIVE: ['=Y'], ID: warehouseIds }
          };
          network.post('/p/cs/list/query', params).then(res1 => {
            this.warehouseListAll = res1.data.rows;
            // if (res1.status == 200 && res1.statusText == 'OK') {
            res1.data.rows.forEach(item => {
              let obj = {
                label: item.WAREHOUSENAME.val,
                value: item.ID.val
              };
              this.warehouseList.push(obj);
            });
            // }
          });
          // }
        });
      },
      resetDialog() { // 重置弹框中数据
        this.LOGISTICSCOMPNAYList = [
          {
            label: '唯品专配',
            value: '120001552'
          }
        ];
        this.warehouseListAll = [];
        this.warehouseList = [];
        this.formInline.LOGISTICSCOMPNAYChoosed = '';
        this.formInline.warehouseChoosed = '';
        this.formInline.ID = '';
        this.$refs.isAirEmbargo.$el.style.display = 'none';
        this.$refs.warehouseChoosed.$el.style.display = 'none';
        this.$refs.selectWarehouse.clearSingleSelect();
      },
      changeStoreChoosed(e) { // 更改店铺选项
        this.resetDialog();
        this.formInline.storeChoosed = e.value;
        this.formInline.storeChoosedName = e.label;
        // 每次店铺选择值发生改变重置选项
        this.$refs.LOGISTICSCOMPNAYNAME.$el.style.display = 'block';
        this.storeListAll.forEach(store => {
          if (e.value == store.ID.val) {
            this.getWarehouseList(store.STOREIDS.refobjid);
            if (store.LOGISTICSCOMPNAYCODE.val == 120001552) {
              this.formInline.LOGISTICSCOMPNAYChoosed = store.LOGISTICSCOMPNAYCODE.val;
              this.$refs.isAirEmbargo.$el.style.display = 'block';
              this.$refs.warehouseChoosed.$el.style.display = 'block';
            } else if (store.LOGISTICSCOMPNAYNAME.val !== '') {
              let obj = {
                label: store.LOGISTICSCOMPNAYNAME.val,
                value: store.LOGISTICSCOMPNAYCODE.val
              };
              this.LOGISTICSCOMPNAYList.unshift(obj);
            }
          }
        });
      },
      changeLOGISTICSCOMPNAYChoosed(value) { // 更改承运商选项
        // if (value == 120001552) {
        this.$refs.isAirEmbargo.$el.style.display = 'block';
        this.$refs.warehouseChoosed.$el.style.display = 'block';
        // } else {
        //   this.$refs.isAirEmbargo.$el.style.display = 'none';
        //   this.$refs.warehouseChoosed.$el.style.display = 'none';
        // }
      },
      changewarehouseChoosed(value) { // 更改发货实体仓库
        this.warehouseListAll.forEach(warehouse => {
          if (value == warehouse.ID.val) {
            // this.formInline.warehouseChoosed = warehouse.JITXWAREHOUSECODE.val; JITXWAREHOUSECODE字段被删除
            this.formInline.ID = warehouse.ID.val;
          }
        });
      },
      cancel() {
        this.$emit('closeActionDialog', true);
      },
      createDelivery() {
        if (!this.formInline.LOGISTICSCOMPNAYChoosed) {
          return this.$Message.info('请选择承运商');
        }
        let isAirEmbargo = '';
        let deliveryMethod = '';
        let logisticsNo = '';
        this.loading = true;
        if (this.formInline.LOGISTICSCOMPNAYChoosed == '120001552') {
          if (this.formInline.is_air_embargo == '否') {
            isAirEmbargo = 0;
          } else {
            isAirEmbargo = 1;
          }
        } else {
          deliveryMethod = '1';
          // logisticsNo = '123456';
          logisticsNo = this.setLogisticNo();
        }
        let params = {
          carrierCode: this.formInline.LOGISTICSCOMPNAYChoosed,
          deliveryMethod,
          deliveryWareHouse: this.formInline.warehouseChoosed,
          warehouseid: this.formInline.ID,
          ids: this.selectRowData[0].ID.val,
          isAirEmbargo,
          logisticsNo,
          sellerNick: this.formInline.storeChoosedName.replace(/(\r\n|\n|\r)/gm, '').trim(),
          shopId: this.formInline.storeChoosed,
          warehouse: this.selectRowData[0].JITWAREHOUSECODE.val,
        };
        this.service.commodityCenter.createPoDelivery(params).then((res) => {
          if (res.data.code === 0) {
            this.$Message.success(res.data.message || '生成成功!');
            // 成功关闭弹框
            this.$emit('closeActionDialog', true);
            this.loading = false;
          } else {
            this.loading = false;
            this.$Message.error(res.data.message || '生成失败!');
          }
        });
      }
    }
  };
</script>

<style lang='less'>
  .createDelivery .ark-select-single .ark-select-selection {
    height: 32px;
    margin-top: -4px;
  }
  .createDelivery .ark-select-single .ark-select-selection .ark-select-placeholder,.createDelivery .ark-select-single .ark-select-selection .ark-select-selected-value {
    height: 30px;
    line-height: 30px;
  }
</style>
<style scoped lang='less'>
  .LOGISTICSCOMPNAYNAME, .isAirEmbargo, .warehouseChoosed {
    display: none;
  }
  .bottomBtnBox {
    width: calc(100% - 48px);
    margin: 16px auto 0px;
    text-align: center;
    .cancelBtn,.sureBtn {
      width: 72px;
      height: 32px;
      font-size: 12px;
    }
    .cancelBtn {
      color: #909399;
      border: 1px solid #DADADA;
      margin-right: 8px;
    }
  }
</style>
