<template>
  <div class="downloadVIPSearchStore">
    <FormLayout
      ref="formLayout"
      :defaultColumn="formLayout.defaultColumn"
      :defaultconfig="formLayout.defaultConfig"
    >
    </FormLayout>
    <businessForm :form-config="formConfig"/>
    <businessButton :btn-config="btnConfig"/>
  </div>
</template>

<script>
  import businessForm from 'professionalComponents/businessForm';
  import businessButton from 'professionalComponents/businessButton';

  export default {
    components: {
      businessForm,
      businessButton
    },
    props: {},
    data() {
      return {
        vmI18n: window.vmI18n,
        PLATFORM: 19,
        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': (e) => {
                    console.log('on-fkrp-selected::e', e);
                    this.formLayout.formValue.shops = e;
                  },
                  'on-clear': () => {
                    console.log('on-clear');
                    this.formLayout.formValue.shops = [];
                  },
                  '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: '=19',
                      }
                    };
                    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: [],
          }
        },
        btnConfig: {
          typeAll: 'error', // 按钮统一风格样式
          btnsite: 'right', // 按钮位置 (right , center , left)
          buttons: [
            {
              type: '', // 按钮类型
              text: window.vmI18n.t('common.cancel'), // 取消 按钮文本
              icon: '', // 按钮图标
              size: '', // 按钮大小
              disabled: false, // 按钮禁用控制
              btnclick: () => {
                this.$emit('closeActionDialog', false);
              } // 按钮点击事件
            },
            {
              type: '', // 按钮类型
              text: window.vmI18n.t('btn.download'), // 下载 按钮文本
              icon: '', // 按钮图标
              size: '', // 按钮大小
              disabled: false, // 按钮禁用控制
              btnclick: () => {
                this.determine();
              }, // 按钮点击事件
            }
          ]
        },
        // 京东淘宝商品下载
        formConfig: {
          formValue: {
            shopId: '',
            startEndTimes: [],
          },
          formData: [
            {
              style: 'date',
              type: 'datetimerange', // 日期组件类型,默认为data  (daterange)为双日期区间选择
              value: 'startEndTimes',
              label: '时间', // 平台修改时间
              width: '24',
              format: 'yyyy-MM-dd HH:mm:ss', // 格式参照burgeonui
              placeholder: '',
              options: {
                disabledDate(time) {
                  let curDate = (new Date()).getTime();
                  let seven = 7 * 24 * 60 * 60 * 1000;
                  let evenDays = curDate - seven;
                  return time.getTime() > curDate || time.getTime() < evenDays;
                  // return time && time.valueOf() >= Date.now() - 86400000;
                }
              },
              onChange: () => {
                // 判断时间间隔,不能小于30分钟
                const timeDiff = this.formConfig.formValue.startEndTimes[1] - this.formConfig.formValue.startEndTimes[0];
                let fz = timeDiff / 60;
                if (fz < 500) {
                  this.$Message.warning('时间间隔不能小于30分钟！');
                }
              }
            },
          ],
          // 表单非空提示
          ruleValidate: {
            // shopId: [{
            //   required: true,
            //   message: ' ',
            //   trigger: 'blur'
            // }],
            startEndTimes: [{
              required: true,
              message: ' ',
              trigger: 'blur'
            }],
          }
        }
      };
    },
    mounted() {
      // this.getShop();
    },
    methods: {
      // formLayout形式获取平台店铺
      async getShop(pageNum = 1, start = 0, range = 10) {
        const query = {
          isdroplistsearch: true,
          refcolid: 198185,
          startindex: (pageNum - 1) * range,
          range,
          fixedcolumns: {
            PLATFORM: '=19',
          }
        };

        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 determine() {
        const formValue = this.formConfig.formValue;
        const formLayoutFormValue = this.formLayout.formValue;
        if (!formLayoutFormValue.shops.length) {
          this.$Message.warning('请选择需要下载的店铺'); // 请选择需要下载的店铺
          return;
        }
        if(formValue.startEndTimes[0] == ""){
          this.$Message.warning('请选择需要下载的时间');
          return;
        }
        let param = {
          platForm: Number(`${this.PLATFORM}`),
          shopId: Number(formLayoutFormValue.shops[0].ID),
        };
        const startDateStr = formValue.startEndTimes[0];
        const endDateStr = formValue.startEndTimes[1];
        // 毫秒
        const startSeconds = Date.parse(startDateStr);
        const endSeconds = Date.parse(endDateStr);
        if (startSeconds) {
          console.log(formValue, 'formValue.startEndTimes');
          const timeDiff = endSeconds - startSeconds;
          console.log('毫秒间隔数:', timeDiff);
          console.log('间隔分钟数:', timeDiff / 1000 / 60);
          if (timeDiff > 7 * 24 * 60 * 60 * 1000) {
            this.$Message.error('最多只支持下载最近7天的数据');
            return false;
          }
          if (timeDiff / 1000 / 60 > 30) {
            this.$Message.error('最大时间间隔30分钟!');
            return false;
          }
          param.startTime = this.$comUtils.dateFormat(formValue.startEndTimes[0], 'yyyy-MM-dd hh:mm:ss');
          param.endTime = this.$comUtils.dateFormat(formValue.startEndTimes[1], 'yyyy-MM-dd hh:mm:ss');
        }

        // 请求下载订单接口
        try {
          const res = await this.service.storageContent.downloadDeliveryOrder(param);
          console.log('请求下载订单接口::res', res);
          if (res.data.code === 0) {
            this.$Message.success('下载任务已发送，请稍后自行查看数据，如无数据，请联系服务人员');
            // 成功关闭弹框
            this.$emit('closeActionDialog', false);
          }
        } catch (e) {
          console.log(e);
          this.$Message.error('系统异常');
        }
      }
    }
  };
</script>

<style scoped>
  @import "~@yunque/css/modal/interfacePlatform/downLoadAll.less";

  .downloadVIPSearchStore /deep/ .formlayout {
    padding-right: 28px;
  }
</style>
