<template>
  <div
    class="jitxDownLoadOrder"
    style="width:430px"
  >
    <Spin
      v-if="spinShow"
      size="large"
      fix
    />
    <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: {
      objList: {
        type: Array,
        defalut: () => []
      },
      idArray: {
        type: Array,
        defalut: () => []
      },
      webid: {
        type: Number
      },
      tablename: {
        type: String
      },
      selectRowData: {
        type: Array,
        defalut: () => []
      }
    },
    // 京东退单接口列表界面(下载退单)
    data() {
      return {
        spinShow: false, // loading动画
        vmI18n: window.vmI18n,
        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: [],
          }
        },
        formConfig: {
          formValue: {
            shopId: '',
            downloadType: 0,
            orderIds: '',
            orderStatus: 1,
            startEndTimes: [],
          },
          formData: [
            {
              style: 'radio', // 单选框
              label: '下载方式', // 订单状态 前面字段
              width: '24', // 宽度
              value: 'downloadType', // 绑定到formValue的值
              radioChange: () => {
                this.radioChangeHandle();
              }, // 切换时的方法
              // setRequired: "required", //必选标识,值不为required时无标识
              options: [
                {
                  label: '按单号下载',
                  value: 0,
                },
                {
                  label: '按时间下载',
                  value: 1,
                }
              ]
            },
            {
              style: 'input', // 输入框类型
              label: '订单号', // 输入框前文字
              value: 'orderIds', // 输入框的值
              width: '24', // 所占的宽度 (宽度分为24份,数值代表所占份数的宽度)
              icon: '', // 输入框后带的图标,暂只有输入框支持
              placeholder: '多个订单编号以逗号分隔', // 占位文本，默认为请输入
              ghost: false, // 是否关闭幽灵按钮，默认开启
              inputenter: () => {
              }, // 表单回车事件
              iconclick: () => {
              } // 点击icon图标事件
              // setRequired: "required" //必选标识,值不为required时无标识
            },
            {
              style: 'select', // 下拉框类型
              label: '订单状态', // 店铺 下拉框前的值
              width: '24', // 所占宽度宽度
              value: 'orderStatus', // 输入框的值
              multiple: false, // 布尔值,下拉框是否开启多选,默认为不开启
              disabled: false, // 是否禁用,默认为false
              clearable: true, // 下拉选中是否显示清空按钮,默认为false
              clearSelect: () => {
              }, // 点击清空按钮回调
              selectChange: () => {
              }, // 选中事件，默认返回选中的值,默认返回当前值value
              setRequired: 'required', // 必选标识,值不为required时无标识
              options: [
                {
                  label: '订单已审核',
                  value: 1,
                },
                {
                  label: '全部',
                  value: 2,
                },
              ]
            },
            {
              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 = 90 * 24 * 60 * 60 * 1000;
                  let evenDays = curDate - seven;
                  return time.getTime() > curDate || time.getTime() < evenDays;
                }
              },
              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'
            }],
            query_date: [{ required: true }]
          }
        },
        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();
              }, // 按钮点击事件
            }
          ]
        },
      };
    },
    mounted() {
      // this.getShop();
      // this.getOrderStatus();
      this.radioChangeHandle();
    },
    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() {
        console.log('下载退单点击确定::this', this);
        const formData = this.formConfig.formData;
        const formValue = this.formConfig.formValue;
        const formLayoutFormValue = this.formLayout.formValue;
        if (!formLayoutFormValue.shops.length) {
          this.$Message.warning('请选择需要下载的店铺'); // 请选择需要下载的店铺
          return;
        }
        let query = {};
        query.shopId = Number(formLayoutFormValue.shops[0].ID);
        if (formValue.downloadType == 0) {
          if (!formValue.orderIds) {
            this.$Message.error('请填写订单号!');
            return false;
          }
          if (formValue.orderIds.split(',').length > 30) {
            this.$Message.error('订单号最多支持30个!');
            return false;
          }
          query.orderIds = formValue.orderIds;
        }
        if (formValue.downloadType == 1) {
          if (!formValue.startEndTimes[0]) {
            this.$Message.error('请填写时间');
            return false;
          }
          const timeDiff = formValue.startEndTimes[1] - formValue.startEndTimes[0];
          console.log('毫秒间隔数:', timeDiff);
          console.log('间隔分钟数:', timeDiff / 1000 / 60);
          if (timeDiff > 90 * 24 * 60 * 60 * 1000) {
            this.$Message.error('最多可支持90天的数据');
            return false;
          }
          if (timeDiff / 1000 / 60 > 30) {
            this.$Message.error('最大时间间隔30分钟!');
            return false;
          }
          query.orderStatus = formValue.orderStatus;
          query.startTime = this.$comUtils.dateFormat(formValue.startEndTimes[0], 'yyyy-MM-dd hh:mm:ss');
          query.endTime = this.$comUtils.dateFormat(formValue.startEndTimes[1], 'yyyy-MM-dd hh:mm:ss');
        }

        try {
          this.spinShow = true;
          const res = await this.service.operationPlatform.downloadPoListByIds(query);
          console.log('res::', res);
          this.spinShow = false;
          if (res.data.code === 0) {
            this.$Message.success('下载任务已发送，请稍后自行查看数据，如无数据，请联系服务人员');
            // 成功关闭弹框
            this.$emit('closeActionDialog', true);
          }
        } catch (error) {
          this.spinShow = false;
        }
      },
      radioChangeHandle() {
        const formValue = this.formConfig.formValue;
        let formData = this.formConfig.formData;
        formData.forEach(item => {
          if (item.value == 'shopId') {
            item.style = 'select';
          } else if (item.value == 'downloadType') {
            item.style = 'radio';
          } else if (item.value == 'orderIds') {
            item.style = 'input';
          } else if (item.value == 'orderStatus') {
            item.style = 'select';
          } else if (item.value == 'startEndTimes') {
            item.style = 'date';
          }
        });
        if (formValue.downloadType == 0) {
          formData.forEach(item => {
            if (['orderStatus', 'startEndTimes'].includes(item.value)) {
              item.style = '';
            }
          });
        } else {
          formData.forEach(item => {
            if (['orderIds'].includes(item.value)) {
              item.style = '';
            }
          });
        }
      }
    },
  };
</script>

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

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