<template>
  <div class="createDelivery" data-key="PRODUCT_DOWNLOAD">
    <Form
      ref="formInline"
      :model="formInline"
      :label-width="110"
    > 
      <FormItem label="店铺" required>
        <DropDownSelectFilter
          single
          :data="dropList"
          :auto-data="searchList"
          :page-size="10"
          :total-row-count="totalCount"
          :columns-key="columnsKey"
          :hidecolumns="hidecolumns"
          :is-back-row-item="true"
          placeholder="请选择"
          @on-popper-show="getSearchData"
          @on-page-change="getSearchData"
          @on-input-value-change="inputSearchData"
          @on-fkrp-selected="selectValue"
          @on-clear="clearValue"
        />
      </FormItem>
      <FormItem v-for="(formItem, index) in currentForms" :key="index" :label="formItem.elemLable">
        <template v-if="formItem.elemType == 'date_time_range'">
          <template v-if="formItem.elemKey == 'create_date_time'">
            <DatePicker
              :vModelFormat="true"
              type="datetimerange"
              format="yyyy-MM-dd HH:mm:ss"
              placeholder=""
              style="width: 100%"
              v-model="formInline.CREATEDTIME"
              @on-change="(val)=> changeCreatedtime({val, type: 'create'})" />
          </template>
          <template v-if="formItem.elemKey == 'update_date_time'">
            <DatePicker
              :vModelFormat="true"
              type="datetimerange"
              format="yyyy-MM-dd HH:mm:ss"
              placeholder=""
              style="width: 100%"
              v-model="formInline.UPDATEDTIME"
              @on-change="(val)=> changeCreatedtime({val, type: 'update'})" />
          </template>
        </template>
        <template v-else-if="formItem.elemType =='input'">
          <Input
            v-model="formInline[formItem.elemKey]"
            placeholder="多个时使用英文逗号分隔"
            style="width: 100%"
          />
        </template>
      </FormItem>
    </Form>
    <div class="bottomBtnBox">
      <Button
        size="small"
        class="cancelBtn"
        ghost
        @click="cancel"
      >
        取消
      </Button>
      <Button
        :loading="loading"
        type="primary"
        size="small"
        class="sureBtn"
        @click="confirmHandle"
      >
        确定
      </Button>
    </div>
  </div>
</template>
<script>
  const R3 = window.R3;

  const { network, urlSearchParams } = R3;
  export default {
    props: {
      selectRowData: {// 获取ID用于多选,获取勾选的明细对应的row内的数据
        type: [Array, Object],
        default: () => {}
      }
    },
    data() {
      return {
        formInline: {
          storeChoosed: '',
          CREATEDTIME: '',//创建时间
          start_time: '',
          end_time: '',
          UPDATEDTIME: '',// 更新时间
          start_create_time: '',// 创建时间开始
          end_create_time: '',// 创建时间结束
          outer_ids: '', // 商家sku编码。要店铺为喵街时有效
        },
        options: {
          disabledDate(time) {
            let curDate = (new Date()).getTime();
            let seven = 90 * 24 * 60 * 60 * 1000;
            let evenDays = curDate - seven;
            return time.getTime() < evenDays;
          }
        },
        loading: false,
        supplierPlaceholder: '请选择',
        dropList: {},
        searchList: [],
        totalCount: 0,
        columnsKey: ['SHOPTITLE'],
        hidecolumns: ['id', 'PLATFORM', 'value'],
        platform: '', // 平台id
        // 不同平台下sku的叫法
        // -------显示选项数据源不可变-----------------
        originForms: {
          outer_ids: {
            elemType: "input",
            elemKey: "outer_ids",
            isRequired: false,
            elemLable: "商品sku",
          },
          creationdate: {//没匹配到就默认给它
            elemType: "date_time_range",
            elemKey: "create_date_time",
            isRequired: false,
            elemLable: "创建时间",
          },
          modifieddate: {
            elemType: "date_time_range",
            elemKey: "update_date_time",
            isRequired: false,
            elemLable: "更新时间",
          },
        },
        // 当前选项的，没匹配到给默认创建时间
        currentForms: [],
        specialLabels: {
          "69": {
            "outer_ids": "平台sku"
          },
          "247": {
            "outer_ids": "商品sku"
          },
          "251": {
            "outer_ids": "商品编码"
          },
        },
        allPlatformFormData: [],//所有平台显示的条件
      };
    },
    created() {
      this.getAllFormList();
    },
    methods: {
      // 获取数据源
      async getAllFormList() {
        try {
          if (this.isRequesting) return;
          this.isRequesting = true;
          const res = await network.get('/p/cs/standitem/window');
          const resultData = res.data || {};
          const { code, data } = resultData || {};
          if (code == 0) {
            this.isRequesting = false;
            this.allPlatformFormData = data || [];
          } else {
            this.isRequesting = false;
          }
        } catch (error) {
          console.log('get_platform_form_error')
        }
      },
      mapSetByPlatformFn() {
        const tempForms = [];
        if (this.allPlatformFormData.length) {
          let str = String(this.platform);
          const filterItem = this.allPlatformFormData.find(obj => Object.keys(obj).includes(str));
          if (filterItem) {
            const arrKeys = filterItem[str] || [];
            const tempLableInfo = this.specialLabels[str] || {};
            console.log(arrKeys, 'filteredArr_key_01')
            if (arrKeys && arrKeys.length) {
              // 过滤当前
              arrKeys.forEach(itemKey => {
                const tempItem = this.originForms[itemKey] || null;
                const curLabel = tempLableInfo[itemKey] || null;
                if (curLabel) tempItem["elemLable"] = curLabel;
                if (tempItem) {
                  tempForms.push(tempItem);
                }
              })
            }
          }
        }
        if (!tempForms.length) {
          const defaultTime = this.originForms["creationdate"];
          tempForms.push(defaultTime);
        }
        this.currentForms = tempForms;
      },
      // 重新匹配条件时要清空
      clearTempFormFn() {
        this.currentForms = [];
        this.formInline.CREATEDTIME = ['', ''];
        this.formInline.start_time = '';
        this.formInline.end_time = '';
        this.formInline.UPDATEDTIME = ['', ''];
        this.formInline.start_create_time = '';
        this.formInline.end_create_time = '';
        this.formInline.outer_ids = '';
      },
      // 查询字段
      async getSearchData(page,value) {
        let startindex = 0;
        if (typeof page === 'number') {
          startindex = (page - 1) * 10;
        }
        const searchdata = {
          isdroplistsearch: true,
          refcolid: 196253,
          fixedcolumns: {},
          startindex,
          range: 10,
        };
        if(value && typeof(value) == 'string'){  // 京东到家店铺模糊搜索后查询整体的表拿到平台
          searchdata.fixedcolumns={'ID':['='+value]}
          this.fuzzyquerybyakList = await this.getKeyList(searchdata);
          let tempPlatformId = "";
          if (typeof this.fuzzyquerybyakList.row[0].PLATFORM == 'object') {
            tempPlatformId = this.fuzzyquerybyakList.row[0].PLATFORM.refobjid;
          } else {
            tempPlatformId = this.fuzzyquerybyakList.row[0].PLATFORM;
          }
          // 清空其他选项，根据平台号重新匹配
          if (this.platform != tempPlatformId) {
            this.platform = tempPlatformId;
            this.clearTempFormFn();
            this.mapSetByPlatformFn();
          }
        }else {
          this.dropList = await this.getKeyList(searchdata);
          this.totalCount = this.dropList.totalRowCount;
        }
      },
      // 请求接口
      async getKeyList(searchdata) {
        return new Promise((resolve) => {
          const api = '/p/cs/QueryList';
          const result = this.commonApi(api, { searchdata }, {
            displayKeys: ['SHOPTITLE'],
          });
          resolve(result);
        });
      },
      commonApi(api, searchdata, options) {
        const { displayKeys } = options;
        return new Promise((resolve) => {
          network
            .post(api, urlSearchParams(searchdata))
            .then((res) => {
              if (res.data.code === 0) {
                const tabth = res.data.data.tabth;
                const row = res.data.data.row;

                let hideColumns = res.data.data.tabth.filter(column => !['SHOPTITLE', 'SELLERNICK', 'PLATFORM'].includes(column.colname) && column.colname != 'ID').map(item => item.colname); // 计算隐藏列，id列要留着

                for (let i = Math.max(tabth.length - 1, 0); i >= 0; i--) {
                  const item = tabth[i];
                  // 让输入框显示 表名称 字段
                  if (displayKeys.includes(item.colname)) {
                    item.isak = true;
                  } else {
                    item.isak = false;
                  }

                  // 隐藏table列
                  if (hideColumns.includes(item.colname)) {
                    tabth.splice(i, 1);
                  }
                }

                if (hideColumns.length > 0) {
                  row.forEach((item) => {
                    for (const key in item) {
                      // 隐藏模糊结果列
                      if (hideColumns.includes(key)) {
                        delete item[key];
                      }
                    }
                  });
                }
                resolve(res.data.data);
              } else {
                resolve({});
              }
            }).catch(() => {
              resolve({});
            });
        });
      },
      inputSearchData(value) {
        if (value === '') {
          this.searchList = [];
          return;
        }
        const params = {
          ak: value,
          colid: 196253,
          fixedcolumns: { whereKeys: {} }
        };

        network.post('/p/cs/fuzzyquerybyak', urlSearchParams(params)).then(res => {
          if (res.data.code == 0) {
            const result = res.data.data || [];
            this.searchList = result;
          }
        });
      },
      selectValue(data) {
        const row = data[0].rowItem;
        
        if(!row.PLATFORM){
          this.getSearchData(1,data[0].ID)
        }
        let tempPlatformId = '';
        if (typeof row.PLATFORM == 'object') {
          tempPlatformId = row.PLATFORM.refobjid;
        } else {
          tempPlatformId = row.PLATFORM;
        }
        // 清空其他选项，根据平台号重新匹配
        if (this.platform != tempPlatformId) {
          this.platform = tempPlatformId;
          this.clearTempFormFn();
          this.mapSetByPlatformFn();
        }
        this.formInline.storeChoosed = data[0].ID;
      },
      clearValue() {
        this.formInline.storeChoosed = '';
      },
      changeCreatedtime(obj) {
        const { val, type } = obj || {};
        if (val[0]) {
          if (type == 'create') {
            this.formInline.start_create_time = val[0];
            this.formInline.end_create_time = val[1];
          } else if (type == 'update') {
            this.formInline.start_time = val[0];
            this.formInline.end_time = val[1];
          }
        }
      },
      cancel() {
        this.$emit('closeActionDialog', true);
      },
      confirmHandle() {
        if (!this.formInline.storeChoosed) {
          return this.$Message.warning('店铺不能为空!');
        }
        // 1、平台编号等于251或408或253，更新时间和商品sku二选一必填；
        // 2、其他平台，只有创建时间则创建时间必填，只有更新时间则更新时间必填，只有sku则无必填校验，创建时间和更新时间都有则二选一必填
        // 校验其他选项是否有值
        const isCanSave = this.checkMustFn();
        if (!isCanSave) return;
        let params = {
          id: this.formInline.storeChoosed,
          start_time: this.formInline.start_time||null,
          end_time: this.formInline.end_time || null,
          outer_ids: this.formInline.outer_ids || '',
          start_create_time: this.formInline.start_create_time || null,
          end_create_time: this.formInline.end_create_time || null,
        };
        network.post('/p/cs/ali/itemdownload', params).then(res => {
          if (res.data.code == 0) {
            this.$Message.success(res.data.message || '下载成功!');
            // 成功关闭弹框
            this.$emit('closeActionDialog', false);
          }
        });
      },
      /**
       * 只有一个选项时该选项必填，如果有2个选项且商品sku存在时有一个必填，如果有3个选项时其中任何一个必填
       */
      checkMustFn() {
        let isCan = true;
        const formCount = this.currentForms.length;
        let errorLable = "";
        let emptyIndex = 0;
        const formKeyInfo = {
          "outer_ids": ["outer_ids"],
          "create_date_time": ["start_create_time", "end_create_time"],
          "update_date_time": ["start_time", "end_time"],
        }
        if (formCount == 1) {
          const { elemKey, elemLable } = this.currentForms[0] || {};
          if (elemKey !== 'outer_ids') {
            const tempValKeys = formKeyInfo[elemKey] || [];
            if (tempValKeys.length) {
              const valKey = tempValKeys[0];
              const curVal = this.formInline[valKey];
              if (!curVal) {
                errorLable = elemLable;
              }
            }
          }
        } else {
          let tempStr = "";
          this.currentForms.forEach((item, index) => {
            const { elemKey, elemLable } = item || {};
            const tempValKeys = formKeyInfo[elemKey] || [];
            if (tempValKeys.length) {
              const valKey = tempValKeys[0];
              const curVal = this.formInline[valKey];
              if (!curVal) {
                emptyIndex += 1;
                tempStr += elemLable;
                if ((index + 1) < formCount) {
                  tempStr += "或者"
                }
              }
            }
          })
          if (emptyIndex == formCount) {
            errorLable = tempStr;
          }
        }
        if (errorLable) {
          this.$Message.warning(`请填写${errorLable}!`);
          isCan = false;
        }
        return isCan;
      }
    }
  };
</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'>
  .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>
