<!--
  门店下拉选择：
  import dailyExport from '@/components/app/cloudDaily/daily-export.vue';
  <daily-export :brandId="brandId" :activeGroupId="activeGroupId"></daily-export>
  components: {
    dailyExport
  }
 -->
<template>
  <div class="daily-export-content">
    <el-form :model="dailyRuleForm" :rules="rules" ref="dailyRuleForm" class="demo-dailyRuleForm">
      <el-form-item label="" prop="dateRange">
        <p class="daily-form-label">选择时间</p>
        <el-date-picker @change="changeDate" class="search-date" format="yyyy-MM-dd" value-format="yyyy-MM-dd" :editable="false" v-model="dailyRuleForm.dateRange" :picker-options="pickerOptions" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"> </el-date-picker>
      </el-form-item>
      <el-form-item label="" prop="storeType">
        <p class="daily-form-label">选择自定义模板</p>
        <el-select class="w-350" v-model="dailyRuleForm.storeType" placeholder="请选择自定义模板" @change="changeTemplate">
          <el-option v-for="item in templates" :key="item.value" :label="item.title" :value="item.storeType"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="stores">
        <p class="daily-form-label">选择门店</p>
        <div class="daily-store-select">
          <el-select class="w-350" v-model="dailyRuleForm.stores" multiple collapse-tags placeholder="请选择">
            <el-option v-for="item in stores" :key="item.value" :label="item.storeName" :value="item.storeId"> </el-option>
          </el-select>
          <div class="show-select-num">已经选择{{ dailyRuleForm.stores.length }}家门店</div>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="exportForm('dailyRuleForm')">导出日报</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { getRequest, postExcel } from '@/api/api';
import errMsg from '@/common/js/error';
import { _debounce } from '@/common/js/public';
export default {
  name: 'daily-export',
  props: {
    brandId: {
      type: String,
      default() {
        return '';
      }
    },
    activeGroupId: {
      type: String,
      default() {
        return '';
      }
    }
  },
  data() {
    return {
      projectName: '', // 当前项目名
      activeBrand: this.brandId, // 品牌 id
      activeGroup: this.activeGroupId, // 传递的品牌分组 id
      dailyRuleForm: {
        dateRange: [],
        storeType: '',
        stores: []
      },
      // 模板数据
      templates: [],
      // 门店数据
      stores: [],
      choiceDateCopy: [],
      pickerOptions: {
        onPick: ({ maxDate, minDate }) => {
          this.choiceDateCopy = [minDate.getTime()];
          if (maxDate) {
            this.choiceDateCopy = [];
          }
        },
        disabledDate: time => {
          if (this.choiceDateCopy.length) {
            const one = 30 * 24 * 3600 * 1000;
            const minTime = this.choiceDateCopy[0] - one;
            const maxTime = this.choiceDateCopy[0] + one;
            return time.getTime() < minTime || time.getTime() > maxTime || time.getTime() > Date.now() - 8.64e6;
          }
          return time.getTime() > Date.now() - 8.64e6;
        }
      },
      rules: {
        dateRange: [{ required: true, message: '请选择日期', trigger: 'change' }],
        storeType: [{ required: true, message: '请选择自定义模板', trigger: 'change' }],
        stores: [{ type: 'array', required: true, message: '请选择门店', trigger: 'change' }]
      }
    };
  },

  methods: {
    /**
     *  选择日期
     */
    changeDate(val) {
      const that = this;
      if (!val) {
        that.choiceDateCopy = [];
        that.dailyRuleForm.dateRange = [];
      }
    },

    /**
     * 选择模板
     */
    changeTemplate() {
      const that = this;
      that.dailyRuleForm.stores = [];
      that.$nextTick(() => {
        that.getStoreData();
      });
    },

    exportForm: _debounce(function(formName) {
      const that = this;
      that.$refs[formName].validate(valid => {
        if (valid) {
          that.postDailyExcel();
        } else {
          return false;
        }
      });
    }, 500),

    postDailyExcel() {
      const that = this;
      let para = {
        filterStoreIds: that.dailyRuleForm.stores.join(',') || '', // 门店分组, 门店
        startDate: that.dailyRuleForm.dateRange[0] || '',
        endDate: that.dailyRuleForm.dateRange[1] || '',
        brandId: that.activeBrand // 品牌 id
      };
      /* let urlSource = `search=${para.search}&filterStoreIds=${para.filterStoreIds}&storeGroupIds=${para.storeGroupIds}&storeType=${para.storeType}&startDate=${para.startDate}&endDate=${para.endDate}&brandId=${para.brandId}&currentPage=${para.currentPage}&pageSize=${para.pageSize}`;
      window.open(`${window.location.origin}/haoban-app-daily-web/daily/batch-export-brand-task?${urlSource}`); */
      postExcel('/haoban-app-daily-web/daily/batch-export-brand-task', para)
        .then(res => {
          if (!res.data) {
            errMsg.errorMsg('暂无数据');
            return false;
          }
          // let resData = res.data;
          const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' });
          const fileName = `云日报记录.csv`;
          const elink = document.createElement('a');
          elink.download = fileName;
          elink.style.display = 'none';
          elink.href = URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();
          URL.revokeObjectURL(elink.href); // 释放URL 对象
          document.body.removeChild(elink);
          // errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },

    /**
     * 获取自定义模板
     */
    getTemplateData() {
      let that = this;
      let para = {
        brandId: that.brandId
      };
      getRequest('/haoban-app-daily-web/daily/list-define-template', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            if (!!resData.result && !!resData.result.length) {
              that.templates = resData.result;
            }
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },

    /**
     * 获取门店
     */
    getStoreData() {
      let that = this;
      let para = {
        brandId: that.activeBrand,
        storeGroupId: that.activeGroup,
        showChild: 1,
        showType: 1,
        status: 1,
        storeType: that.dailyRuleForm.storeType,
        pageNum: 1,
        pageSize: 100000
      };
      getRequest('/haoban-manage-web/store/findSimplePage', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            that.stores = resData.result.list || [];
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }
  },
  watch: {
    brandId: function(newData, oldData) {
      const that = this;
      if (!!newData) {
        that.dailyRuleForm.storeType = '';
        that.activeBrand = newData;
        that.getTemplateData();
      }
    },
    activeGroupId: function(newData, oldData) {
      let that = this;
      if (!!newData) {
        that.activeGroup = newData;
      }
    }
  },
  mounted() {
    const that = this;
    if (!!that.brandId) {
      that.activeBrand = that.brandId;
      that.activeGroup = that.activeGroupId;
      that.getTemplateData();
    }
  }
};
</script>
<style lang="less" scoped>
.daily-export-content {
  width: 500px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;

  .w-350 {
    width: 350px;
  }

  .daily-form-label {
    font-size: 12px;
    color: #909399;
  }

  .daily-store-select {
    position: relative;
    .show-select-num {
      position: absolute;
      left: 2px;
      top: 3px;
      width: 318px;
      height: 28px;
      color: #606266;
      font-size: 14px;
      background: #fff;
      pointer-events: none;
      z-index: 2;
    }
  }
}
</style>
