<template>
  <div class="mall-section-container">
    <div class="mall-content-section">
      <div class="mall-content-title">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '' }">
            <a href="/report/#/memberSummary">首页</a>
          </el-breadcrumb-item>
          <el-breadcrumb-item>积分商城</el-breadcrumb-item>
          <el-breadcrumb-item>设置</el-breadcrumb-item>
          <el-breadcrumb-item>配送设置</el-breadcrumb-item>
        </el-breadcrumb>
        <h3>
          <span>配送设置</span>
        </h3>
      </div>
      <div class="section">
        <div style="border-bottom:1px solid #dcdfe6;padding:24px;">
          <div class="header-top" style="display:inline-block;margin-right:30px;padding:12px 0px" v-if="$getButtonLimit($buttonCode.deliverSetSelfTake)">
            <span style="width:80px;">门店自提 </span>
            <el-switch v-model="pickStatus" @change="changeStatus" :limit-code="$buttonCode.deliverSetSelfTake" />
          </div>
          <div
            class="header-top"
            v-show="pickStatus"
            style="display:inline-block;background:#F0F2F5;padding:12px 20px"
            v-if="$getButtonLimit($buttonCode.deliverAutoVerification)"
          >
            <span>会员自助核销
              <el-tooltip effect="dark" content="若开启“会员自助核销”，那么对于自提积分兑换订单，在小程序端将展示“提货核销”按钮，会员可在到店后输入导购提供的导购代码，自助核销掉自提订单。" placement="top-start">
                <i class="iconfont icon-xinxixianshi" />
              </el-tooltip>
            </span>
            <el-switch
              v-model="cancelStatus"
              @change="changeCancelStatus"
              :disabled="!pickStatus"
              :limit-code="$buttonCode.deliverAutoVerification"
            />
          </div>
        </div>

        <div v-show="pickStatus" style="padding:24px;">
          <div class="operate-top">
            <div class="fl">
              <div class="search-item m-r-10">
                <el-input
                  v-model="searchValue"
                  placeholder="请输入自提点名称/code"
                  prefix-icon="el-icon-search"
                  clearable
                  class="w-280"
                  @keyup.enter.native="getSearchList"
                  @clear="getSearchList"
                />
              </div>
              <div class="search-item m-r-10">
                <el-autocomplete
                  prefix-icon="el-icon-search"
                  popper-class="autocomplete-wrap"
                  class="inline-input"
                  :value="creatorName"
                  :select-when-unmatched="true"
                  @change.native="changeAuto"
                  @select="selectCreator"
                  :fetch-suggestions="querySearch"
                  placeholder="请输入创建人"
                  :trigger-on-focus="false"
                >
                  <template slot-scope="{ item }">
                    {{ item.creatorName }}
                  </template>
                </el-autocomplete>
              </div>
              <div class="search-item">
                <el-select
                  v-model="isValid"
                  placeholder="自提点状态"
                  clearable
                  class="w-140"
                  @change="getSearchList"
                >
                  <el-option label="失效" :value="0" />
                  <el-option label="正常" :value="1" />
                </el-select>
              </div>
            </div>
            <div class="fr">
              <el-button
                plain
                @click="exportData"
                style="margin:0 10px 0 0"
                v-if="$getButtonLimit($buttonCode.deliverSetExport)"
                :limit-code="$buttonCode.deliverSetExport"
              >
                <i class="iconfont icon-icon_yunxiazai" style="margin-right:5px" />导出自提点
              </el-button>
              <el-button
                plain
                @click="setPicked"
                style="margin:0 10px 0 0"
                v-if="$getButtonLimit($buttonCode.deliverSet)"
                :limit-code="$buttonCode.deliverSet"
              >
                自提设置
              </el-button>
              <el-button
                plain
                @click="multipleClose"
                style="margin:0 10px 0 0"
              >
                <i style="margin-right:5px" />批量失效
              </el-button>
              <el-button
                type="primary"
                @click="addStore('-1')"
                style="margin:0 "
                v-if="$getButtonLimit($buttonCode.deliverSetAdd)"
                :limit-code="$buttonCode.deliverSetAdd"
              >
                新增自提点
              </el-button>
            </div>
          </div>
          <div v-loading="loading">
            <el-table
              ref="multipleTable"
              :data="tableDate"
              style="width: 100%"
              @selection-change="handleSelectAll"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="pickUpPointName" label="自提点名称" min-width="200px" />
              <el-table-column prop="storeCode" label="自提点code" min-width="100" />
              <el-table-column prop="pickUpPointAddress" label="自提点地址" min-width="200px" />
              <el-table-column prop="pickUpPointPhone" label="联系电话" />
              <el-table-column prop="canChooseTime" label="自提时间可选" min-width="150px">
                <template slot-scope="scope">
                  <span>{{ scope.row.canChooseTime === 1 ? '是' : '否' }}</span>
                </template>
              </el-table-column>
              <el-table-column label="状态">
                <template slot-scope="scope">
                  <span>{{ scope.row.isValid === 1 ? '正常' : '失效' }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="creatorName" label="创建人" min-width="150px" />
              <el-table-column label="操作" min-width="150px">
                <template slot-scope="scope">
                  <div>
                    <el-button
                      type="text"
                      @click="goAdd(scope.row)"
                      v-if="$getButtonLimit($buttonCode.deliverSetEdit)"
                      :limit-code="$buttonCode.deliverSetEdit"
                    >
                      编辑
                    </el-button>
                    <el-popover
                      placement="top"
                      width="160"
                      v-model="scope.row.visible2"
                      style="margin-left:8px"
                    >
                      <p style="line-height:1.5;padding: 10px 10px 20px;">
                        确定删除该自提点吗？
                      </p>
                      <div style="text-align: right; margin: 0">
                        <el-button size="mini" type="text" @click="scope.row.visible2 = false">
                          取消
                        </el-button>
                        <el-button type="primary" size="mini" @click="deletePoint(scope.row, scope.$index)">
                          确定
                        </el-button>
                      </div>
                      <el-button
                        slot="reference"
                        type="text"
                        v-if="$getButtonLimit($buttonCode.deliverSetDelete)"
                        :limit-code="$buttonCode.deliverSetDelete"
                      >
                        删除
                      </el-button>
                    </el-popover>
                    <el-button type="text" @click="open(scope.row)" v-if="scope.row.isValid !== 1">
                      启用
                    </el-button>
                  </div>
                </template>
              </el-table-column>
              <template slot="empty">
                <div class="no-data-wrap">
                  <div class="no-data-icon">
                    <img src="../../../static/img/no-data_icon.png">
                  </div>
                  <p>暂无数据</p>
                </div>
              </template>
            </el-table>
            <div class="pagination-conteiner" v-show="tableDate.length > 0">
              <div class="pagination">
                <dm-pagination
                  v-if="total != 0"
                  background
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :current-page="currentPage"
                  :page-sizes="pageSizes"
                  :page-size="pageSize"
                  layout="total, sizes, prev, pager, next"
                  :total="total"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 自提点设置 -->
    <pickedAuto :pickedForm="pickedForm" :visible.sync="pickedVisible" @getList="getList" />
    <!-- 导出自提点 -->
    <vue-gic-export-excel
      :dataArr="tableDate"
      :dialogVisible.sync="dialogVisible"
      :type="2"
      :excelUrl="excelUrl"
      :params="params"
      :projectName="projectName"
    />
  </div>
</template>

<script>
import qs from 'qs';
import request from '../../service/request.js';
// import getInputVal from '../../../utils/common.js';
// import stockModal from '../../../components/getSkuList';
import pickedAuto from './pickedAuto';
import { alertInfo } from '../../utils/user.js';
export default {
  components: {
    pickedAuto,
  },
  data () {
    return {
      searchValue: '',
      isValid: '',
      creatorId: '',
      creatorName: '',
      currentPage: 1,
      pageSizes: [20, 40, 60, 80],
      pageSize: 20,
      total: 2,
      pickStatus: true, // 自提状态
      cancelStatus: false, // 核销状态
      loading: false,
      selectList: [], // 复选框选中的数据
      tableDate: [],
      creatorOptions: [],
      pickedForm: {
        selectIdList: [], // 复选框选中的数据的id
        list: [{ timeRange: [] }], // 初始数据
      },
      pickedVisible: false,
      creatorLoading: false,
      enableAccessControl: false,
      // 导出
      dialogVisible: false,
      excelUrl: '/api-integral-mall/pick-up-points-excel',
      params: { search: '', dataType: 2, requestProject: 'integral-mall' },
      projectName: 'integral-mall',
    };
  },
  created () {
    this.getAccessControl();
    // export const alertInfo = () => {
    //   Notification({
    //     title: '温馨提示',
    //     type: 'warning',
    //     message: '在此页面进行修改、删除等操作将更改本商户下所有的配置 请谨慎进行'
    //   });
    // }
    this.enableAccessControl = localStorage.getItem('enableAccessControl') != 'false';
    if (this.enableAccessControl) {
      alertInfo();
    }
    this.getStatus();
  },
  methods: {
    changeAuto (e) {
      if (!e.target.value) {
        this.creatorId = '';
        this.creatorName = '';
        // this.getSearchList();
      }
    },
    selectCreator (v) {
      this.creatorName = '';
      this.creatorId = '';
      this.$nextTick(() => {
        this.creatorName = v.creatorName;
        this.creatorId = v.creatorId;
        this.getSearchList();
      });
    },
    querySearch (v, cb) {
      this.creatorLoading = true;
      const params = {
        creatorName: v,
      };
      request.get('/api-integral-mall/list-creator', { params }).then(res => {
        if (res.data.errorCode === 0) {
          if (res.data.result) {
            cb(res.data.result);
          } else {
            // eslint-disable-next-line node/no-callback-literal
            cb([]);
          }
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    getAccessControl () {
      const params = {
        requestProject: 'integral-mall',
      };
      request.get('/api-auth/get-login-user-info', { params }).then(res => {
        if (res.data.errorCode === 0) {
          if (res.data.result.enableAccessControl) {
            this.enableAccessControl = true;
          } else {
            this.enableAccessControl = false;
          }
          window.localStorage.setItem('enableAccessControl', this.enableAccessControl);
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    getSearchList () {
      this.currentPage = 1;
      this.getList();
    },
    // 分页设置每页的数量
    handleSizeChange (size) {
      this.pageSize = size;
      this.getList();
    },
    // 分页设置跳转到第几页
    handleCurrentChange (page) {
      this.currentPage = page;
      this.getList();
    },
    // 复选
    handleSelectAll (val) {
      this.selectList = val;
    },
    // 自提设置
    setPicked () {
      if (this.selectList.length < 1) {
        this.$message.error('请先选择自提点');
        return false;
      } else {
        this.pickedForm.selectIdList = [];
        for (const item of this.selectList) {
          this.pickedForm.selectIdList.push(item.integralMallPickUpPointId);
        }
        const currentTime = new Date(new Date().valueOf());
        const currentTime1 = new Date(new Date(new Date().getTime() + 1000 * 60).valueOf());
        // this.pickedModal.timeRangeList[0].timeRange = [currentTime, currentTime1];
        this.pickedForm.list[0].timeRange = [currentTime, currentTime1];
        this.pickedVisible = true;
      }
    },
    // 获取自提点状态
    getStatus () {
      request.get('/api-integral-mall/pick-up-point-switch-status').then(res => {
        if (res.data.errorCode === 0) {
          if (res.data.result.status === 0) {
            this.pickStatus = false;
          } else if (res.data.result.status === 1) {
            this.pickStatus = true;
          }
          if (res.data.result.memberVerification === 0) {
            this.cancelStatus = false;
          } else if (res.data.result.memberVerification === 1) {
            this.cancelStatus = true;
          }
          this.getList();
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    // 修改自提点状态
    changeStatus () {
      const params = {
        status: this.pickStatus ? 1 : 0,
      };
      request.get('/api-integral-mall/set-pick-up-point-switch-status', { params }).then(res => {
        if (res.data.errorCode === 0) {
          this.$message.success('设置成功');
          this.getStatus();
          this.getList();
        } else {
          this.pickStatus = !this.pickStatus;
          this.$message.error(res.data.message);
        }
      });
    },
    // 开启关闭会员核销
    changeCancelStatus () {
      const params = {
        status: this.cancelStatus ? 1 : 0,
      };
      request.get('/api-integral-mall/set-pick-up-point-member-verification', { params }).then(res => {
        if (res.data.errorCode === 0) {
          this.$message.success('设置成功');
          // this.getList();
        } else {
          this.cancelStatus = !this.cancelStatus;
          this.$message.error(res.data.message);
        }
      });
    },
    // 删除自提点
    deletePoint (item, index) {
      const params = {
        integralMallPickUpPointId: item.integralMallPickUpPointId,
      };
      request.get('/api-integral-mall/delete-pick-up-point', { params }).then(res => {
        if (res.data.errorCode === 0) {
          this.tableDate.splice(index, 1);
          if (this.tableDate.length === 0) {
            if (this.currentPage > 1) {
              this.currentPage = this.currentPage - 1;
            }
          }
          this.getList();
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    getList () {
      const params = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        search: this.searchValue,
        isValid: this.isValid,
        creatorId: this.creatorId,
      };
      this.loading = true;
      request.post('/api-integral-mall/page-pick-up-points', qs.stringify(params)).then(res => {
        if (res.data.errorCode === 0) {
          if (res.data.result.result) {
            this.tableDate = res.data.result.result;
            this.total = res.data.result.totalCount;
          } else {
            this.tableDate = [];
            this.total = 0;
          }
          this.loading = false;
        } else {
          this.$message.error(res.data.message);
          this.loading = false;
        }
      });
    },
    multipleClose () {
      if (this.selectList.length < 1) {
        this.$message.error('未选择任何自提点，不能操作批量失效');
        return;
      }
      this.$confirm(`您已选择${this.selectList.length}个自提点，是否确认操作批量失效？操作后这些自提点将不能用于门店自提商品的自提`, '提示', {
        type: 'warning',
      }).then(_ => {
        this.loading = true;
        const integralMallPickUpPointIdList = this.selectList.map(item => item.integralMallPickUpPointId);
        request.post('/api-integral-mall/unvalid-pick-up-point', { integralMallPickUpPointIdList }).then(res => {
          this.$message.success('失效成功');
          this.getList();
        }).finally(_ => {
          this.loading = false;
        });
      });
    },
    // 新增
    addStore () {
      this.$router.push({ name: 'addDeliver', query: { integralMallPickUpPointId: '-1' } });
    },
    // 编辑
    goAdd (item) {
      this.$router.push({ name: 'editDeliver', query: { integralMallPickUpPointId: item.integralMallPickUpPointId } });
    },
    open (row) {
      request.post('/api-integral-mall/valid-pick-up-point', { integralMallPickUpPointId: row.integralMallPickUpPointId }).then(res => {
        this.$message.success('启用成功,该自提点可用于门店自提商品的自提');
        this.getList();
      });
    },
    // 导出数据
    exportData () {
      const params = {
        search: this.searchValue,
      };
      request
        .post('/api-integral-mall/pick-up-points-excel', qs.stringify(params))
        .then(res => {
          if (res.data.errorCode === 0) {
            setTimeout(() => {
              window.open(window.location.origin + '/gic-web/#/reportCenter', '_self');
            }, 1000);
          } else {
            this.$message.error(res.data.message);
            return false;
          }
        })
        .catch(error => {
          this.$message.error({
            duration: 1000,
            message: error.message,
          });
          return false;
        });
      // this.dialogVisible = true;
      // this.params.search = this.searchValue;
    },
  },
};
</script>
<style scoped>
.m-r-10 {
  margin-right: 10px;
}
.w-140 {
  width: 140px;
}
.w-280 {
  width: 280px;
}
.section {
  background: #fff;
  margin: 24px;
  padding: 0;
}
.header-top {
  /* margin: 15px 0 22px 0; */
}
.header-top span {
  width: 130px;
  display: inline-block;
}
</style>
