<template>
  <div class="DownLoadPickList">
    <FormLayout
      ref="formLayout"
      class="formlayout"
      :default-column="formLayout.defaultColumn"
      :defaultconfig="formLayout.defaultConfig"
    />
    <Form
      ref="formModel"
      :model="formModel"
      :rules="formRule"
      :label-width="80"
    >
      <!--      <FormItem-->
      <!--        label="店铺"-->
      <!--        prop="shopId"-->
      <!--      >-->
      <!--        <Select-->
      <!--          v-model="formModel.shopId"-->
      <!--          placeholder="请选择"-->
      <!--          filterable-->
      <!--        >-->
      <!--          <Option-->
      <!--            v-for="item in shops"-->
      <!--            :key="item.ID.val"-->
      <!--            :value="item.ID.val"-->
      <!--          >{{ item.SHOPTITLE.val }}</Option>-->
      <!--        </Select>-->
      <!--      </FormItem>-->
      <FormItem
        label="下载方式"
        prop="downloadType"
      >
        <RadioGroup
          v-model="formModel.downloadType"
          @on-change="downloadTypeRadioChange($event)"
        >
          <Radio label="0">
            根据PO号
          </Radio>
          <Radio label="1">
            根据拣货单号
          </Radio>
        </RadioGroup>
      </FormItem>
      <template v-if="downloadTypeSwitchAreaDisplay">
        <FormItem
          label="PO号"
          prop="poNOs"
        >
          <Select
            v-model="formModel.poNOs"
            placeholder="请选择"
            filterable
            multiple
            choose-all
            multiple-type
          >
            <Option
              v-for="item in poNOs"
              :key="item.PO_NO.val"
              :value="item.PO_NO.val"
            >
              {{ item.PO_NO.val }}
            </Option>
          </Select>
        </FormItem>
        <FormItem
          label="JIT仓库"
          prop="jitWarehouseCodes"
        >
          <Select
            v-model="formModel.jitWarehouseCodes"
            placeholder="请选择"
            filterable
            multiple
            choose-all
            multiple-type
          >
            <Option
              v-for="item in jitWarehouses"
              :key="item.ID.val"
              :value="item.JITWAREHOUSECODE.val"
            >
              {{ item.JITWAREHOUSENAME.val }}
            </Option>
          </Select>
        </FormItem>
      </template>
      <FormItem
        v-else
        label="拣货单号"
        prop="pickNOs"
      >
        <Input
          v-model="formModel.pickNOs"
          :rows="3"
          placeholder="可填写多个，用英文逗号隔开"
        />
      </FormItem>
    </Form>
    <footer style="display: flex; justify-content: flex-end; margin-top: 16px">
      <Button
        type="fcdefault"
        @click="cancel()"
      >
        取消
      </Button>
      <Button
        type="posdefault"
        style="margin-left: 8px;"
        @click="submit()"
      >
        确定
      </Button>
    </footer>
  </div>
</template>

<script lang="js">
  import common from '@yunque/service/modules/common';
  import vip from '@yunque/service/modules/vipCenter';
  import { showModalFcSuccess, showModalFcError, formatDate } from '@yunque/service/modules/utils';

  export default {
    name: 'DownLoadPickList',
    props: {
      selectRowData: { // 获取选择行的数据
        type: Array,
        default: () => []
      },
      idArray: {// 获取ID用于多选
        type: [Array, Object],
        default: () => {
        }
      },
    },
    data() {
      const validatePoNOs = (rule, value, callback) => {
        if (!value || value.length <= 0) {
          callback(new Error('请选择 PO 号'));
        } else {
          callback();
        }
      };
      const validateWarehouseCodes = (rule, value, callback) => {
        if (!value || value.length <= 0) {
          callback(new Error('请选择 JIT 仓库'));
        } else {
          callback();
        }
      };
      return {
        PLATFORM: {
          // 淘宝商品
          T_V_IESTAOBAOITEM: 2,
          // 京东商品
          T_IESJINGDONGWARE: 4,
          T_V_IESJINGDONGWARE: 4,
          // 唯品会商品
          T_IESVIPSKU: 19,
          T_V_OMSPICKORDER: 19,
          // 淘宝分销商品
          T_IESTAOBAOFXITEM: 3,
          // 通用商品 TODO 后台沟通这个版本没有
          T_IESSTANDPLATSKU: '',
        },
        shops: [],
        formLayout: {
          defaultColumn: 1,
          defaultConfig: [
            {
              item: {
                type: 'DropDownSelectFilter',
                required: true,
                label: '店铺',
                props: {
                  disabled: false,
                  totalRowCount: 100,
                  pageSize: 10,
                  hidecolumns: ['ID'],
                  showColnameKey: 'isak', // 选中展示字段：对应表头需要增加改字段为true（isak：true）
                  AutoData: [],
                  defaultSelected: [],
                  data: {
                    start: 0,
                    totalRowCount: 70,
                    pageSize: 10,
                    tabth: [],
                    row: []
                  },
                },
                style: {
                  width: 60,
                },
                event: {
                  'on-fkrp-selected': async (e) => {
                    console.log('on-fkrp-selected::e', e);
                    this.formLayout.formValue.shops = e;
                    // 加载 PO 号信息
                    if (e.length > 0) {
                      await this.getPoNos(e[0].ID);
                    }
                  },
                  'on-clear': () => {
                    console.log('on-clear');
                    this.formLayout.formValue.shops = [];
                    // 清空 PO 号的加载数据源和选择值
                    this.poNOs = [];
                    this.formModel.poNOs = [];
                  },
                  'on-popper-show': async () => {
                    console.log('on-popper-show');
                    this.getShop();
                  },
                  'on-page-change': (value) => {
                    console.log('on-page-change', value);
                    this.getShop(value);
                  },
                  'on-input-value-change': async (value) => {
                    console.log('on-input-value-change::val', value);
                    let fd = new FormData();
                    fd.append('ak', value);
                    fd.append('colid', 198185);
                    const fixedcolumns = {
                      whereKeys: {
                        PLATFORM: `=${this.PLATFORM[this.$route.params.tableName]}`,
                      }
                    };
                    fd.append('fixedcolumns', JSON.stringify(fixedcolumns));
                    const res = await this.service.common.fuzzyquerybyak(fd);
                    console.log('on-input-value-change::fuzzyquerybyak::res', res);
                    if (res.data.code === 0) {
                      this.formLayout.defaultConfig[0].item.props.AutoData = res.data.data;
                    }
                  }
                }
              }
            },
          ],
          formValue: {
            shops: [],
          }
        },
        jitWarehouses: [],
        poNOs: [], // 下拉框绑定的数据源
        formModel: {
          shopId: undefined,
          downloadType: '0',
          poNOs: [], // 选中的PO号
          jitWarehouseCodes: [],
          _pickNOs: '', // 拣货单号
          get pickNOs() {
            return this._pickNOs;
          },
          set pickNOs(value) {
            this._pickNOs = value.replace(/，/g, ',');
          }
        },
        formRule: {
          shopId: [
            {
              required: true,
              message: '请选择店铺',
              trigger: 'blur'
            }
          ],
          downloadType: [{ required: true }],
          poNOs: [{
            required: true,
            validator: validatePoNOs,
            trigger: 'change'
          }],
          jitWarehouseCodes: [{
            required: true,
            validator: validateWarehouseCodes,
            trigger: 'change'
          }],
          pickNOs: [{
            required: true,
            message: '请输入拣货单号',
            trigger: 'blur'
          }]
        }
      };
    },
    async mounted() {
      window.DownLoadPickList = this;
      this.getJITWarehouse();
    },
    computed: {
      downloadTypeSwitchAreaDisplay() {
        return this.formModel.downloadType === '0';
      }
    },
    methods: {
      async getShop(pageNum = 1, start = 0, range = 10) {
        const query = {
          isdroplistsearch: true,
          refcolid: 198185,
          startindex: (pageNum - 1) * range,
          range,
          fixedcolumns: {
            PLATFORM: '=19',
            JITSHOPTYPE: '1,3'
          }
        };

        const fd = new FormData();
        fd.append('searchdata', JSON.stringify(query));
        const res = await this.service.common.QueryList(fd);
        console.log('getShop::res', res);
        if (res.data.code == 0) {
          let data = {
            start,
            totalRowCount: res.data.data.totalRowCount,
            pageSize: range,
            tabth: res.data.data.tabth,
            row: res.data.data.row
          };
          this.formLayout.defaultConfig[0].item.props.data = data;
          this.formLayout.defaultConfig[0].item.props.totalRowCount = res.data.data.totalRowCount;
        }
      },
      async getJITWarehouse() {
        // 获取"JIT仓库"信息
        let jitWarehouseRsp = await common.listQuery({
          table: 'T_V_IESJITWAREHOUSE',
          fixedcolumns: {
            ISACTIVE: '=Y'
          },
          range: 1000
        });
        if (jitWarehouseRsp) {
          this.jitWarehouses.push(...jitWarehouseRsp.rows);
        }
      },
      /**
       * 获取 PO 号
       * @returns {Promise<void>}
       */
      async getPoNos(shopid) {
        let poNosRsp = await common.listQuery({
          table: 'T_OMSJITPOLIST',
          fixedcolumns: {
            SHOPID: shopid,
            ISACTIVE: '=Y',
            SELL_ET_TIME: `${formatDate(new Date(), 'yyyy/MM/dd hh:mm:ss')}~${new Date().getFullYear() + 100}/12/31 23:59:59`
          },
          range: 5000,
          isdroplistsearch: true,
          fkdrplist: {
            searchcols: ['PO_NO', 'SELL_ET_TIME'],
            orderby: [
              {
                column: 'PO_NO',
                asc: true
              }
            ]
          }
        });
        if (poNosRsp && poNosRsp.rows) {
          this.poNOs = poNosRsp.rows;
          this.formModel.poNOs = [];
        }
      },
      // formLayout形式获取平台店铺
      submit() {
        const formLayoutFormValue = this.formLayout.formValue;
        this.$refs.formModel.validate(async (valid) => {
          if (!valid) {
            this.$Message.error('请完成必输项的选择或输入!');
          } else {
            try {
              // let shopModel = this.shops.filter(a => a.ID.val === this.formModel.shopId)[0];
              if (!formLayoutFormValue.shops.length) {
                this.$Message.error('请选择店铺!');
                return false;
              }
              let param = {
                shopId: Number(formLayoutFormValue.shops[0].ID),
                // vendorId: shopModel.VENDOR_ID.val,
              };
              if (this.formModel.downloadType === '0') {
                param.po = this.formModel.poNOs.join(',');
                param.warehouseCode = this.formModel.jitWarehouseCodes.join(',');
              } else {
                param.pickNo = this.formModel.pickNOs;
              }

              let downloadResult = await vip.downloadPickList(param);
              if (downloadResult.code !== 0) {
                showModalFcError('友情提示', downloadResult.message);
              } else {
                showModalFcSuccess('友情提示', downloadResult.message);
                this.$emit('closeActionDialog');
              }
            } catch (e) {
              console.error(e);
              showModalFcError('错误', `系统出现异常，请联系管理员（${e}）`);
            }
          }
        });
      },
      cancel() {
        this.closeDialog();
      },
      closeDialog() { // 关闭弹窗
        this.$emit('closeActionDialog', true);
      },
      downloadTypeRadioChange(e) {
        console.log('downloadTypeRadioChange::e', e);
      }
    }
  };
</script>

<style scoped>
  .DownLoadPickList form {
    margin-right: 30px;
  }

  .DownLoadPickList /deep/ .formlayout .formlayout-label {
    width: 80px !important;
  }

  .DownLoadPickList /deep/ .formlayout .formlayout-div {
    padding-right: 34px !important;
  }
</style>
