<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2019-07-05 10:29:46
 * @LastEditors: 无尘
 * @LastEditTime: 2020-08-26 09:54:06
 -->
<!--
  门店下拉选择：
  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="inline-block 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="inline-block 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="inline-block daily-form-label">选择门店：</p>
        <el-popover placement="bottom" title="" width="350" trigger="click" v-model="storeVisible">
          <div class="daily-store-select">
            <div class="select-search">
              <el-input placeholder="请输入门店名称" maxlength="50" v-model="searchSelect" style="width: 100%;" @keyup.native="value => toInput(value, searchSelect)" @clear="clearSearch"> <i slot="prefix" class="el-input__icon el-icon-search"></i> </el-input>
            </div>
            <div class="checkbox border-box" style="padding: 15px 20px;">
              <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
            </div>
            <div class="el-scrollbar define-search-select">
              <div class="el-select-dropdown__wrap el-scrollbar__wrap" style="margin-bottom: -5px; margin-right: -5px;">
                <el-checkbox-group v-model="dailyRuleForm.stores" @change="handleStoresChange">
                  <ul class="el-scrollbar__view el-select-dropdown__list">
                    <li :class="['el-select-dropdown__item', item.select ? 'selected hover' : '']" v-for="item in stores" :key="item.storeId">
                      <!-- @click="checkStore(item)" -->
                      <!--  <span>{{ item.storeName }}</span> -->
                      <el-checkbox :label="item.storeId">{{ item.storeName }}</el-checkbox>
                    </li>
                    <li v-if="!stores.length" class="text-center"><span>暂无数据</span></li>
                  </ul>
                </el-checkbox-group>
              </div>
              <div class="el-scrollbar__bar is-horizontal"><div class="el-scrollbar__thumb" style="transform: translateX(0%);"></div></div>
              <div class="el-scrollbar__bar is-vertical"><div class="el-scrollbar__thumb" style="transform: translateY(0%);"></div></div>
            </div>
          </div>
          <div class="show-select-num w-350" slot="reference" @click="changeVisible">
            已经选择{{ dailyRuleForm.stores.length }}家门店
            <span class="el-input__suffix"
              ><span class="el-input__suffix-inner"><i :class="['el-select__caret el-input__icon el-icon-arrow-up', storeVisible ? 'is-reverse' : '']"></i></span
            ></span>
          </div>
        </el-popover>
      </el-form-item>
      <el-form-item>
        <p class="inline-block daily-form-label m-t-50"></p>
        <el-button type="primary" :loading="loadingBtn" @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: [],
      // 门店数据
      checkAll: false,
      isIndeterminate: false,
      searchSelect: '',
      storeVisible: false,
      stores: [],
      storesCopy: [],
      choiceDateCopy: [],
      pickerOptions: {
        onPick: ({ maxDate, minDate }) => {
          this.choiceDateCopy = [minDate.getTime()];
          if (maxDate) {
            this.choiceDateCopy = [];
          }
        },
        disabledDate: time => {
          if (this.choiceDateCopy.length) {
            const one = 90 * 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' }]
      },
      pageNum: 1,
      pageSize: 200,
      loadingBtn: false
    };
  },

  methods: {
    /**
     * 全选
     */
    handleCheckAllChange(val) {
      const that = this;
      that.dailyRuleForm.stores = val ? that.stores.map(item => item.storeId) : [];
      that.isIndeterminate = false;
    },
    handleStoresChange(value) {
      const that = this;
      let checkedCount = value.length;
      that.checkAll = checkedCount === that.stores.length;
      that.isIndeterminate = checkedCount > 0 && checkedCount < that.stores.length;
    },
    /**
     *  选择日期
     */
    changeDate(val) {
      const that = this;
      if (!val) {
        that.choiceDateCopy = [];
        that.dailyRuleForm.dateRange = [];
      }
    },

    /**
     * 选择模板
     */
    changeTemplate() {
      const that = this;
      that.pageNum = 1;
      that.dailyRuleForm.stores = [];
      that.stores = [];
      that.storesCopy = [];
      that.searchSelect = '';
      that.checkAll = false;
      that.isIndeterminate = false;
      that.$nextTick(() => {
        that.getStoreData();
      });
    },

    exportForm: _debounce(function(formName) {
      const that = this;
      that.loadingBtn = true;
      that.$refs[formName].validate(valid => {
        if (valid) {
          that.$alert('数据查询量较大，导出时间较长，请耐心等待!', '', {
            confirmButtonText: '确定',
            callback: action => {}
          });
          let templateId = '';
          that.templates.forEach(ele => {
            if (ele.storeType == that.dailyRuleForm.storeType) {
              templateId = ele.dailyReportTemplateId;
            }
          });
          that.postDailyExcel(templateId);
        } else {
          that.loadingBtn = false;
          return false;
        }
      });
    }, 500),

    postDailyExcel(templateId) {
      const that = this;
      let para = {
        storeIds: that.dailyRuleForm.stores.join(',') || '', // 门店分组, 门店
        templateId: templateId,
        startDate: that.dailyRuleForm.dateRange[0] || '',
        endDate: that.dailyRuleForm.dateRange[1] || '',
        enterpriseId: that.activeBrand // 品牌 id
      };
      postExcel('/haoban-app-daily-three-web/daily/batch-export', para)
        .then(res => {
          that.loadingBtn = false;
          if (!res.data) {
            errMsg.errorMsg('暂无数据');
            return false;
          }
          const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' });
          const fileName = `${that.dailyRuleForm.dateRange[0]}-${that.dailyRuleForm.dateRange[1]}日报.xls`;
          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);
        })
        .catch(function(error) {
          that.loadingBtn = false;
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },

    /**
     * 输入
     */
    toInput: _debounce(function(e, value) {
      const that = this;
      if (!that.storesCopy.length) {
        return false;
      }
      if (value == '') {
        that.stores = JSON.parse(JSON.stringify(that.storesCopy));
      }
      let filterData = JSON.parse(JSON.stringify(that.storesCopy)).filter(ele => {
        return ele.storeName.includes(value);
      });
      that.stores = filterData;
    }, 500),

    /**
     * 显示或隐藏门店列表
     */
    /* eslint-disable */
    changeVisible() {
      // const that = this;
      // that.storeVisible = !that.storeVisible;
    },

    /**
     * 选择门店
     */
    checkStore(item) {
      const that = this;
      if (item.select) {
        item.select = false;
        const index = that.dailyRuleForm.stores.indexOf(item.storeId);
        that.dailyRuleForm.stores.splice(index, 1);
      } else {
        item.select = true;
        that.dailyRuleForm.stores.push(item.storeId);
      }
      that.storesCopy.forEach(ele => {
        if (that.dailyRuleForm.stores.includes(ele.storeId)) {
          ele.select = true;
        }
      });
    },

    /**
     * 清空
     */
    clearSearch() {
      const that = this;
      that.stores = JSON.parse(JSON.stringify(that.storesCopy));
    },

    /**
     * 获取自定义模板
     */
    getTemplateData() {
      const that = this;
      let para = {
        enterpriseId: that.brandId
      };
      getRequest('/haoban-app-daily-three-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 = {
        enterpriseId: that.activeBrand,
        storeGroupId: that.activeGroup,
        showChild: 1,
        showType: 1,
        status: 1,
        storeType: that.dailyRuleForm.storeType,
        pageNum: that.pageNum,
        pageSize: that.pageSize
      };
      getRequest('/haoban-manage3-web/store/find-simple-page', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            if (resData.result.list) {
              resData.result.list.forEach(ele => {
                ele.select = false;
              });
            }
            if (that.pageNum == 1) {
              that.stores = JSON.parse(JSON.stringify(resData.result.list)) || [];
              that.storesCopy = JSON.parse(JSON.stringify(resData.result.list)) || [];
            }else {
              resData.result.list.forEach(ele => {
                that.stores.push(ele);
                that.storesCopy.push(ele);
              })
            }
            if (that.pageNum*that.pageSize < resData.result.total) {
              that.pageNum ++;
              that.getStoreData();
            }
            // console.log('that.stores:',that.stores)
            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.dailyRuleForm.stores = [];
        that.stores = [];
        that.storesCopy = [];
        that.searchSelect = '';
        that.checkAll = false;
        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>
.select-search {
  width: 100%;
  // padding: 0 10px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

.m-t-50 {
  margin-top: 50px;
}

.el-form-item {
   /deep/ .el-form-item__error {
    left: 120px;
   }
 }

.define-search-select {
  ul {
    li {
      &.selected:after {
        position: absolute;
        right: 20px;
        font-family: element-icons;
        content: '\E611';
        font-size: 12px;
        font-weight: 700;
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
      }
    }
  }
}
.daily-export-content {
  width: 500px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;

  .w-350 {
    width: 350px;
  }

  .daily-form-label {
    width: 115px;
    text-align: right;
    font-size: 14px;
    color: #606266;
  }

  .show-select-num {
    position: relative;
    display: inline-block;
    font-size: inherit;
    height: 32px;
    line-height: 32px;
    padding-left: 10px;
    -webkit-appearance: none;
    background-color: #fff;
    background-image: none;
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    color: #606266;
    .el-select__caret {
      color: #c0c4cc;
      font-size: 14px;
      transition: transform 0.3s;
      transform: rotate(180deg);
      cursor: pointer;
      &.is-reverse {
        transform: rotate(0deg);
      }
    }
  }

  .daily-store-select {
    position: relative;
  }
}
</style>
