<template>
  <div>
    <!-- 自提点类型 -->
    <el-select style="width: 160px" :value="isNaN(Number(data.shopSelectType)) ? '' : Number(data.shopSelectType)" @change="onTypeChange">
      <el-option v-for="el in pickupType" :key="el.value" :label="el.label" :value="el.value"></el-option>
    </el-select>
    <!-- 部分自提点 穿梭框 -->
    <el-popover v-if="data.shopSelectType == 1" v-model="isFocus" placement="bottom-start" trigger="click">
      <el-input
        placeholder="请选择自提点"
        slot="reference"
        :class="['transfer-trigger', { 'is-focus': isFocus }]"
        :value="data.shopCodeList.length > 0 ? `已选择 ${data.shopCodeList.length} 家` : ''">
        <i slot="suffix" class="el-input__icon el-icon-arrow-down"></i>
      </el-input>
      <!-- 穿梭框 -->
      <el-transfer
        class="transfer"
        filterable
        filter-placeholder="请输入门店名称/code"
        :value="data.shopCodeList"
        :titles="['所有门店', '已选门店']"
        :filter-method="onFilterStore"
        :props="{ key: 'storeCode', label: 'name' }"
        :data="pickupList"
        @change="onTransferChange">
        <div slot-scope="{ option }" class="transfer-item">
          <el-tooltip popper-class="transfer-tip" :content="option.name" placement="top-start" v-if="option.nameIsOverflow">
            <p class="store-name">{{ option.name }}</p>
          </el-tooltip>
          <p class="store-name" v-else>{{ option.name || '--' }}</p>
          <p class="store-code">{{ option.storeCode || '--' }}</p>
        </div>
      </el-transfer>
    </el-popover>
    <!-- 批量导入 -->
    <div class="pickup-upload" v-if="data.shopSelectType == 2">
      <!-- 导入 -->
      <dm-upload-file
        accept=".xls,.xlsx"
        with-credentials
        :action="api.giftShopListUpload"
        :headers="{ isControl: true }"
        :data="{ giftId }"
        :show-file-list="false"
        :before-upload="onBeforeUpload"
        :on-success="onUploadSucc">
        <el-button class="upload-trigger"><i class="iconfont-components4 icon-cp-shangc upload-icon"></i> 上传</el-button>
        <div slot="tip" class="upload-tip">
          <el-button style="margin-right: 30px" type="text" @click="onDownloadTemplate">下载文件模板</el-button>
          <el-popover trigger="click" placement="right" popper-class="upload-popper">
            <el-button slot="reference" type="text">查看导入规则</el-button>
            <div class="upload-tip-text">
              <p>1. 自提点code请至自提设置中导出；<el-button type="text" @click="toSetting">前去设置</el-button></p>
              <p>2. 重新导入后将会覆盖原有全部门店；</p>
              <p>3. 上传完整仅支持.xlsx .xls文件的导入，填充数据不超过“5000”条。</p>
            </div>
          </el-popover>
        </div>
        <div slot="file-item" slot-scope="{fileData}">{{ fileData.name }}</div>
      </dm-upload-file>
      <!-- 上传的文件列表 -->
      <div class="pickup-list" v-if="isEdit && uploadFile.status == 0 && data.shopNum != 0">
        <!-- 编辑时展示示上传成功的数量 -->
        <p class="pickup-list-total">
          共上传<span class="pickup-list-number">{{ data.shopNum || 0 }}</span>个自提点
          <el-button type="text" class="download-pickup" @click="downloadPickup">
            <i class="iconfont-welfare4 icon-xiazai download-icon"></i>
          </el-button>
        </p>
      </div>
      <!-- 上传成功后展示文件名，导入成功的数量，导入失败的数量，失败原因 -->
      <div class="pickup-list" v-if="uploadFile.status == 1">
        <p class="pickup-list-name">
          <i class="iconfont-welfare4 icon-wenjian1 file-icon"></i>
          {{ uploadFile.name }}
          <el-button type="text" class="download-pickup" @click="downloadPickup">
            <i class="iconfont-welfare4 icon-xiazai download-icon"></i>
          </el-button>
        </p>
        <p class="pickup-list-total">
          成功<span class="pickup-list-success">{{ uploadFile.successNum || 0 }}</span>个，失败<span class="pickup-list-error">{{ uploadFile.errorNum || 0 }}</span>个。
          <el-button type="text" v-if="uploadFile.errorNum" @click="showErrorList = true">查看失败原因</el-button>
        </p>
      </div>
    </div>
    <el-dialog title="查看失败原因" :visible.sync="showErrorList" width="500" class="error-list">
      <div v-for="(el, index) in uploadFile.errorList" :key="index" class="error-item">{{ el }}</div>
    </el-dialog>
  </div>
</template>

<script>
/**
 * 所有自提点
 * 部分自提点
 *  获取所有自提点
 *  回显时根据礼品id获取当前礼品的所有自提点-由组件外部获取，取到之后通过data.shopCodeList传入
 * 批量导入
 *  上传礼品自提点列表
 *  部分自提点时的回显，只需要回显导入的数量
 *  新增时需要回显导入的数量，和导入的文件名称
 */

// 组件的返回结果
/**
 * {
 *    shopSelectType: 1,
 *    shopCodeList: [],
 *    shopImportUuid: 123
 * }
 */
import { origin, welfarePrefix } from '@/config/index.js';
import api from '@/api/gift.js';
const { getPickupList } = api;
export default {
  name: 'SelectPickupStore',
  props: {
    // 是否是编辑，true：编辑 false：新增
    isEdit: {
      type: Boolean,
      default: false
    },
    giftId: String, // 礼品id
    data: {
      type: Object,
      default: () => ({
        shopSelectType: '', // 自提点类型
        shopCodeList: [], // 穿梭框选中的门店code
        shopNum: '', // 批量导入的数量
      })
    }
  },
  data() {
    return {
      api: {
        giftShopListUpload: `${welfarePrefix}/gift/gift-shop-list-upload`, // 上传礼品自提点列表EXCEL
        giftShopListDownload: `${welfarePrefix}/gift/gift-shop-list-download`, // 下载礼品自提点列表EXCEL
        downloadGiftTemplate: '/static/自提点模板.xlsx', // 下载模板
      },
      // 自提点类型 0 所有自提点 1 部分自提点 2 批量导入
      pickupType: [
        { label: '所有门店', value: 0 },
        { label: '部分门店', value: 1 },
        { label: '批量导入', value: 2 },
      ],
      // 部分自提点-输入框是否处于焦点
      isFocus: false,
      // 部分自提点-穿梭框的选项数据
      pickupList: [],
      // 批量导入-上传的文件
      uploadFile: {
        status: 0, // 文件上传状态 0：从未上传过 1：上传成功 其他上传不成功
        name: 'text', // 文件名
        successNum: 0, // 导入成功的数量
        errorNum: 0, // 导入失败的数量
        errorList: [], // 导入失败的错误原因
      },
      // 查看失败原图的弹窗
      showErrorList: false,
    };
  },
  created() {
    this.init();
    // 组件创建后，如果this.data.shopSelectType == ''时，需要主动触发一下onTypeChange事件，将shopSelectType = 0传给调用方
    if (typeof this.data.shopSelectType != 'number' || this.data.shopSelectType == '') {
      this.onTypeChange(0);
    }
  },
  mounted() {
    document.addEventListener('click', this.onClosePopover, true);
    document.addEventListener('visibilitychange', this.init);
  },
  beforeDestroy() {
    document.removeEventListener('click', this.onClosePopover, true);
    document.removeEventListener('visibilitychange', this.init);
  },
  methods: {
    init() {
      if (document.visibilityState != 'visible') return;
      // 获取所有自提点
      this.pickupList = [];
      const getList = (currentPage) => {
        getPickupList({ currentPage, pageSize: 20 }).then(res => {
          const { result } = res.result || {};
          if (Array.isArray(result) && result.length > 0) {
            this.pickupList = this.pickupList.concat(result.map(el => {
              el.nameIsOverflow = this.getOffsetWidth(el.name) > 129;
              return el;
            }));
            getList(currentPage + 1);
          }
        });
      };
      getList(1);
    },
    // 获取字符串的offsetWidth宽度
    getOffsetWidth(str) {
      const span = document.createElement('span');
      span.style.position = 'fixed';
      span.style.top = '-100%';
      span.style.left = '-100%';
      span.style.zIndex = -1;
      span.style.opacity = 0;
      span.innerHTML = str;
      document.body.appendChild(span);
      const width = span.offsetWidth;
      document.body.removeChild(span);
      return width;
    },
    // 改变自提点类型，需要重置shopCodeList和shopImportUuid
    onTypeChange(shopSelectType) {
      this.isFocus = false;
      this.$emit('change', Object.assign({}, this.data, { shopSelectType, shopCodeList: [], shopImportUuid: '' }));
    },
    // 部分自提点-保存选择的自提点code
    onTransferChange(shopCodeList) {
      this.$emit('change', Object.assign({}, this.data, { shopCodeList }));
    },
    // 部分自提点-穿梭框的搜索方法
    onFilterStore(query, item) {
      return (typeof item.name == 'string' && item.name.indexOf(query) >= 0) || item.storeCode.toString().indexOf(query) >= 0;
    },
    // 点击下拉列表时，关闭部分自提点的popover
    onClosePopover(event) {
      const parentNode = event.target.parentNode;
      if (parentNode && parentNode.parentNode.className.indexOf('el-select') >= 0) {
        this.isFocus = false;
      }
    },
    // 去设置自提点code
    toSetting() {
      window.open(`${origin}/welfare/setting/pickup-list`);
    },
    // 自提点上传-模板下载
    onDownloadTemplate() {
      // eslint-disable-next-line
      const basePath = process.env['NODE_ENV'] === 'development' ? '' : '/welfare';
      window.location.href = `${basePath}${this.api.downloadGiftTemplate}`;
    },
    // 自提点上传-上传之前
    onBeforeUpload(file) {
      this.uploadFile.name = file.name;
      this.uploadFile.status = 2;
    },
    // 自提点上传-上传成功
    onUploadSucc(res) {
      const { successNum, errorNum, errorList } = res.result;
      while(errorList.length < 5) {
        errorList.push('第一行：code 填入值格式不合法');
      }
      Object.assign(this.uploadFile, { status: 1, successNum, errorNum, errorList });
    },
    // 自提点下载
    downloadPickup() {
      window.location.href = `${origin}${this.api.giftShopListDownload}?giftId=${this.giftId}`;
    },
  }
};
</script>

<style lang="scss" scoped>
@import '@/assets/styles/colors.scss';
.transfer-trigger {
  margin-left: 10px;
  width: 160px;
  &::before {
    content: '';
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 1;
    width: 100%;
    height: 100%;
    background: transparent;
    cursor: pointer;
  }
  &:focus {
    outline: none;
  }
  &.is-focus {
    /deep/ .el-input__inner {
      border-color: $blue;
      box-shadow: 0 0 0 2px rgba(47, 84, 237, 0.2);
    }
    .el-input__icon {
      transform: rotateZ(-180deg);
    }
  }
}
.transfer {
  /deep/ .el-transfer-panel__item {
    padding-top: 8px;
    padding-bottom: 8px;
    width: 100%;
    height: auto;
    line-height: normal;
    .el-checkbox__input {
      top: 10px;
    }
  }
  /deep/ .el-transfer-panel__empty::before {
    content: '';
    display: block;
    margin: 0 auto;
    width: 30px;
    height: 30px;
    background: url('../../../assets/images/no-data_icon1.png') center no-repeat;
    background-size: contain;
  }
  /deep/ .el-transfer-panel__header  {
    pointer-events: none;
    .el-checkbox__input {
      display: none;
    }
  }
  .transfer-item {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: flex-start;
    .store-name {
      width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      font-size: 14px;
      font-weight: 400;
      color: $gray01;
      line-height: 22px;
    }
    .store-code {
      font-size: 12px;
      font-weight: 400;
      color: $gray01;
      line-height: 16px;
    }
  }
  /deep/ .el-transfer__buttons .el-button {
    padding: 0;
    width: 24px;
    min-width: 24px;
    &:first-child {
      margin-bottom: 0;
      transform: translateY(calc(100% + 4px));
    }
    &:last-child {
      transform: translateY(-100%);
    }
  }
}
.pickup-upload {
  display: inline-block;
  vertical-align: top;
  margin-left: 10px;
  .upload-trigger {
    border-style: dashed;
    .upload-icon {
      font-size: 14px;
    }
  }
  .upload-tip {
    display: inline-block;
  }
  .pickup-list {
    margin-top: 18px;
    .pickup-list-name {
      font-size: 14px;
      font-weight: 400;
      color: $gray01;
      line-height: 20px;
      .file-icon {
        font-size: 14px;
      }
    }
    .download-pickup {
      margin-left: 8px;
    }
    .pickup-list-total {
      margin-top: 8px;
      font-size: 12px;
      font-weight: 400;
      color: $gray03;
      line-height: 17px;
      .pickup-list-number, .pickup-list-success, .pickup-list-error {
        padding: 0 5px;
      }
      .pickup-list-number {
        color: $gray01;
      }
      .pickup-list-success {
        color: $green-success;
      }
      .pickup-list-error {
        color: $red-error;
      }
    }
  }
}
.upload-tip-text {
  width: 308px;
  p {
    font-size: 12px;
    font-weight: 400;
    color: #303133;
    line-height: 16px;
    & + p {
      margin-top: 9px;
    }
  }
}
.error-item {
  font-size: 14px;
  font-weight: 400;
  color: $gray01;
  line-height: 20px;
  & + .error-item {
    margin-top: 10px;
  }
}
.error-list {
  /deep/ .el-dialog__body {
    max-height: 400px;
    overflow-y: auto;
  }
}
</style>
<style>
.upload-popper {
  padding: 10px 12px!important;
}
.transfer-tip {
  width: auto !important;
}
</style>
