<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2018-10-10 14:44:45
 * @LastEditors: 无尘
 * @LastEditTime: 2020-09-27 13:49:51
 -->
<template>
  <div class="unreview-wrap common-set-wrap">
    <div class="right-content">
      <div class="right-box" style="min-height: calc(100vh - 86px)">
        <div class="reviewed-body-head flex flex-space-between">
          <div>
            <el-input class="w-344" maxlength="50" placeholder="请输入提交人姓名/账号/手机号" prefix-icon="el-icon-search" v-model="searchValue" clearable @clear="clearSearch" @keyup.native="value => searchEnterFun(value, searchInput)"> </el-input><el-select v-model="auditType" placeholder="全部事项" @change="changeTableList" class="w-130 m-l-10"> <el-option v-for="item in filterOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option> </el-select><el-select v-model="filterBrand" placeholder="全部品牌" @change="changeTableList" class="w-168 m-l-10">
              <el-option label="全部品牌" value=""></el-option>
              <el-option v-for="item in brandOptions" :key="item.enterpriseId" :label="item.enterpriseName" :value="item.enterpriseId"> </el-option>
            </el-select>
          </div>
          <dm-perm-button :disabled="$itemPerm($itemCode.batchAudit)" type="primary" @click="approveAll">批量同意</dm-perm-button>
        </div>
        <div class="reviewed-body-content">
          <el-table ref="multipleTable" v-loading="loading" :data="tableData" tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column label="审核事项">
              <template slot-scope="scope">
                <span v-if="scope.row.auditType == 1">导购账号绑定</span>
                <span v-if="scope.row.auditType == 3">导购账号新增</span>
              </template>
            </el-table-column>
            <el-table-column label="提交人" show-overflow-tooltip>
              <template slot-scope="scope">
                <div class="flex">
                  <el-popover placement="top" width="300" trigger="hover" @show="showSingleInfo(scope.row.submitStaffId)">
                    <div class="apply-info-detail">
                      <div class="flex">
                        <div class="apply-info-img flex-align-center flex-pack-center bg-82c5ff ">
                          <img v-if="userData.headImg" :src="userData.headImg" alt="img" />
                          <img v-else src="../../assets/member.png" alt="img" />
                        </div>
                        <div class="flex flex-column apply-info-right flex-pack-center">
                          <div class="apply-info-name">
                            <span class="font-14 color-303133">{{ userData.staffName || '--' }}</span> <span class="font-14 color-90939">( {{ userData.sex == 1? '男' : userData.sex == 2? '女' : '--' }})</span>
                          </div>
                        </div>
                      </div>
                      <div class="flex flex-space-between line-26 m-t-15">
                        <div class="font-14 color-606266">账号</div>
                        <div class="font-14 color-303133">{{ userData.wxUserId || '--' }}</div>
                      </div>
                      <div class="flex flex-space-between line-26">
                        <div class="font-14 color-606266">职务</div>
                        <div class="font-14 color-303133">{{ userData.postion || '--' }}</div>
                      </div>
                      <div class="flex flex-space-between line-26">
                        <div class="font-14 color-606266">手机号</div>
                        <div class="font-14 color-303133">{{ userData.nationCode || '--' }}-{{ userData.phoneNumber || '--' }}</div>
                      </div>
                      <div class="flex flex-space-between line-26">
                        <div class="font-14 color-606266 w-m-100">部门</div>
                        <div class="font-14 color-303133">{{ userData.departmentInfo.map(ele => ele.departmentName).join(';') || '--' }}</div>
                      </div>
                    </div>
                    <div slot="reference">
                      <div class="flex flex-align-center flex-pack-center bg-82c5ff table-head-pic cursor-pointer">
                        <img v-if="scope.row.submitHeadImg" :src="scope.row.submitHeadImg" alt="img" />
                        <img v-else src="../../assets/member.png" alt="img" />
                      </div>
                    </div>
                  </el-popover>
                  <div class="flex flex-column apply-info hide-ellipsis">
                    <span class="font-14 color-606266 hide-ellipsis">{{ scope.row.submitStaffName || '--' }}</span>
                    <span class="font-12 color-909399 hide-ellipsis">{{ scope.row.submitWxUserId || '--' }}</span>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="详情" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.content || '--' }}
              </template>
            </el-table-column>
            <el-table-column label="提交时间" show-overflow-tooltip>
              <template slot-scope="scope">
                <div class="line-h-18">{{ scope.row.createTime | timeStampToYmd }}</div>
                <div class="line-h-18">{{ scope.row.createTime | timeStampToHms }}</div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template slot-scope="scope">
                <el-button @click="handleClick(scope.$index, scope.row)" type="text">同意</el-button>
                <el-button @click="handleClick(scope.$index, scope.row, 'refuse')" type="text">拒绝</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="block common-wrap__page text-right" v-if="tableData.length != 0">
            <dm-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[20, 40, 60, 80]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"> </dm-pagination>
          </div>
        </div>
      </div>
    </div>
    <!-- 门店变更 -->
    <store-change v-model="showStoreDialog" :store-change-data="storeChangeData"> </store-change>
    <!-- 同意 -->
    <el-dialog class="approve-dialog" title="" :visible.sync="approveVisible" width="422px">
      <div class="approve-body text-center">
        <div><i class="el-icon-success"></i><span class="approve-icon-tip">同意</span></div>
        <div class="approve-tip">是否确认同意</div>
      </div>
      <div slot="footer" class="approve-footer dialog-footer" style="text-align: center;">
        <el-button @click="approveVisible = false">取 消</el-button>
        <el-button type="primary" @click="sendApprove">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 拒绝 -->
    <el-dialog class="refuse-dialog" title="提示" :visible.sync="refuseVisible" :before-close="cancelRefuse" width="422px">
      <div>
        <div class="refuse-tip">请输入拒绝理由</div>
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="demo-ruleForm">
          <el-form-item label="" prop="refuseReason">
            <el-input class="font-14" v-model="ruleForm.refuseReason" type="textarea" placeholder="最多 50 个字" :rows="3"> </el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="approve-footer dialog-footer">
        <el-button @click="cancelRefuse('ruleForm')">取 消</el-button>
        <el-button type="primary" @click="sendRefuse('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>
    <review-result-detail :audit-ids="auditIds" :success-count="successCount" :fail-count="failCount" :table-list-data="tableListData" :detail-show="detailShow" @hideDetailDialog="hideDetailDialog"> </review-result-detail>

    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
      <span>共{{ multipleSelection.length }}条审核事项，是否批量同意?</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="loadBtn" @click="postAllApprove(multipleSelection.map(item => item.auditId).join(','))">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import storeChange from '@/components/review/store-change.vue';
import reviewResultDetail from '@/components/review/review-result-detail.vue';
import showMsg from '@/common/js/showmsg';
import { _debounce, emojiToStr } from '@/common/js/public';
import fetch from '@/api/review.js';
import api from '@/api/contact.js';
const { getStaffDetail } = api;
const { getReview, getWxEnterprise, postAudit, postBatchApprove, postRefuse, getAuditDetail } = fetch;
export default {
  name: 'UnreviewPage',
  components: {
    storeChange,
    reviewResultDetail
  },
  data() {
    return {
      wxEnterpriseId: localStorage.getItem('haoBanUser') ? JSON.parse(localStorage.getItem('haoBanUser')).wxEnterpriseId : '',
      auditName: localStorage.getItem('haoBanUser') ? JSON.parse(localStorage.getItem('haoBanUser')).staffName : '',
      auditType: '', // 筛选的事项
      filterBrand: '', // 筛选的品牌
      brandOptions: [], // 品牌列表
      searchValue: '',
      filterOptions: [
        {
          label: '全部事项',
          value: ''
        },
        {
          label: '导购账号绑定',
          value: '1'
        },
        {
          label: '导购账号新增',
          value: '3'
        }
      ],
      loading: false,
      tableData: [],
      multipleSelection: [],

      // 分页参数
      currentPage: 1,
      pageSize: 20,
      total: 0,

      // 操作
      selectId: '',
      ruleForm: {
        refuseReason: ''
      },
      rules: {
        refuseReason: [
          {
            required: true,
            message: '拒绝理由不能为空',
            trigger: 'change'
          },
          {
            min: 1,
            max: 50,
            message: '长度在 1 到 50 个字',
            trigger: 'change'
          }
        ]
      },

      showStoreDialog: false,
      storeChangeData: {
        beforeContent: [],
        afterContent: []
      },

      approveVisible: false,
      refuseVisible: false,

      detailShow: false, // 批量审核详情显示
      resultShow: false, // 批量审核显示
      tableListData: [], // 审核详情的数据
      resultText: '',
      failCount: 0,
      successCount: 0,
      // user
      userData: {
        staffName: '',
        phoneNumber: '',
        nationCode: '',
        postion: '',
        departmentInfo: [],
        headImg: '',
        wxUserId: '',
        sex: 1
      },
      dialogVisible: false,
      loadBtn: false,
      timeFlag: null,
      loadingFull: ''
    };
  },
  mounted() {
    const that = this;
    that.$emit('showTab', '/unreview');
    // that.wxEnterpriseId = await that.toLogin();
    that.getTableList();
    that.getBrandData();
  },
  beforeDestroy() {       // 清除定时器
    window.clearInterval(this.timeFlag);
    this.timeFlag = null;
  },
  methods: {
    /**
     * @description: 搜索标签清空
     * @author: 无尘
     */
    clearSearch() {
      const that = this;
      that.currentPage = 1;
      that.getTableList();
    },
    changeTableList() {
      const that = this;
      that.currentPage = 1;
      that.getTableList();
    },

    /**
     * @description: 搜索标签
     * @param {Object} e
     * @author: 无尘
     */
    searchEnterFun: _debounce(function(e) {
      const that = this;
      let searchVal = String(e.target.value).trim();
      if (!searchVal) {
        return false;
      }
      that.currentPage = 1;
      that.getTableList();
    }, 200),
    /**
     * @description: 关闭详情
     * @author: 无尘
     */
    hideDetailDialog() {
      const that = this;
      that.detailShow = false;
      that.currentPage = 1;
      that.getTableList();
    },

    /**
     * @description: 表格---多选
     * @param {Array} val
     * @author: 无尘
     */
    handleSelectionChange(val) {
      const that = this;
      that.multipleSelection = val;
    },

    /**
     * @description: 分页---页码变化
     * @param {Number} val
     * @author: 无尘
     */
    handleSizeChange(val) {
      const that = this;
      that.currentPage = 1;
      that.pageSize = val;
      that.getTableList();
    },

    /**
     * @description: 分页---当前页变化
     * @param {Number} val
     * @author: 无尘
     */
    handleCurrentChange(val) {
      const that = this;
      that.currentPage = val;
      that.getTableList();
    },

    /**
     * @description: 操作
     * @param {Number} index
     * @param {Object} item
     * @param {String} flag
     * @returns {Boolean}
     * @author: 无尘
     */
    handleClick(index, item, flag) {
      const that = this;
      that.selectId = item.auditId;
      !!flag ? (that.refuseVisible = true) : '';
      if (!!flag) {
        return false;
      }
      that
        .$confirm('是否确认同意?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          that.sendApprove();
        })
        .catch(() => {
          that.selectId = '';
        });
    },

    /**
     * @description: 确定同意
     * @author: 无尘
     */
    sendApprove: _debounce(function() {
      const that = this;
      that.postApprove(that.selectId);
    }, 500),
    postApprove(ids) {
      const that = this;
      let para = {
        auditId: ids,
        auditName: that.auditName
      };
      postAudit(para)
        .then(res => {
          if (res.code == '0000') {
            showMsg.showmsg('操作成功', 'success');
            that.approveVisible = false;
            that.currentPage = 1;
            that.getTableList();
            that.$forceUpdate();
          }else {
            that.currentPage = 1;
            that.getTableList();
            that.$message({
              message: res.message || '接口异常',
              type: 'warning'
            });
          }
        })
        .catch(function(error) {

        });
    },

    /**
     * @description: 批量同意
     * @returns {Boolean}
     * @author: 无尘
     */
    approveAll: function() {
      const that = this;
      let ids = !!that.multipleSelection.length ? that.multipleSelection.map(item => item.auditId).join(',') : '';
      if (!ids) {
        that.$message({
          message: '请至少选择一条审核事项',
          type: 'warning'
        });
        return false;
      }
      that.dialogVisible = true;
    },

    postAllApprove(ids) {
      const that = this;
      that.loadBtn = true;
      let para = {
        auditIds: ids,
        auditName: that.auditName
      };
      postBatchApprove(para)
        .then(res => {
          that.loadBtn = false;
          if (res.code == '0000') {
            that.dialogVisible = false;
            that.$nextTick(()=> {
              that.loadingFull = that.$loading({
                lock: true,
                text: '数据处理中,请耐心等待',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
              });
              window.clearInterval(that.timeFlag);
              that.timeFlag = null;
              that.timeFlag = window.setInterval(() => {
                that.getDetailFlag();
              }, 3000);
              that.$once('hook:beforeDestroy', () => {
                window.clearInterval(that.timeFlag);
                that.timeFlag = null;
              });
            });
          }else {
            that.$message({
              message: res.message || '接口异常',
              type: 'warning'
            });
          }
        })
        .catch(function(error) {
          that.loadBtn = false;
        });
    },
    getDetailFlag() {
      const that = this;
      let para = {
        auditIds: that.multipleSelection.map(item => item.auditId).join(',') || ''
      };
      getAuditDetail(para)
        .then(res => {
          if (res.result.auditResult) {
            that.auditIds = that.multipleSelection.map(item => item.auditId).join(',');
            that.loadingFull.close();
            window.clearInterval(that.timeFlag);
            that.timeFlag = null;
            that.tableListData = res.result.resultList || [];
            that.failCount = res.result.fail || 0;
            that.successCount = res.result.success || 0;
            that.detailShow = true;
            that.currentPage = 1;
            that.getTableList();
          }else {
            that.tableListData = [];
            that.detailShow = false;
          }
        })
        .catch(function(error) {});
    },

    /**
     * @description: 取消拒绝
     * @param {String} formName
     * @author: 无尘
     */
    cancelRefuse(formName) {
      const that = this;
      that.refuseVisible = false;
      that.$refs['ruleForm'].resetFields();
    },

    /**
     * @description: 确定拒绝
     * @param {String} formName
     * @author: 无尘
     */
    sendRefuse: _debounce(function(formName) {
      const that = this;
      that.$refs[formName].validate(valid => {
        if (valid) {
          that.postRefuseData();
        } else {
          return false;
        }
      });
    }, 500),

    postRefuseData() {
      const that = this;
      let para = {
        auditName: that.auditName,
        auditId: that.selectId,
        reason: emojiToStr(that.ruleForm.refuseReason)
      };
      postRefuse(para)
        .then(res => {
          if (res.code == '0000') {
            showMsg.showmsg('操作成功', 'success');
            that.refuseVisible = false;
            that.$refs['ruleForm'].resetFields();
            that.currentPage = 1;
            that.getTableList();
          }else {
            that.$message({
              message: res.message || '接口异常',
              type: 'warning'
            });
            that.currentPage = 1;
            that.getTableList();
          }
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },

    /**
     * @description: 获取头像处显示信息
     * @param {String} submitStaffId
     * @author: 无尘
     */
    showSingleInfo(submitStaffId) {
      const that = this;
      const para = {
        staffId: submitStaffId
      };
      getStaffDetail(para)
        .then(res => {
          that.userData = res.result || {
            staffName: '',
            phoneNumber: '',
            nationCode: '',
            postion: '',
            departmentInfo: [],
            headImg: '',
            wxUserId: '',
            sex: 1
          };
        })
        .catch(function(error) {

        });
    },

    /**
     * @description: 显示门店变更
     * @param {object} item
     * @author: 无尘
     */
    showStoreChange(item) {
      const that = this;
      that.storeChangeData = {
        beforeContent: [],
        afterContent: []
      };
      that.showStoreDialog = true;
      that.storeChangeData = {
        beforeContent: item.oldValue != '' ? item.oldValue.split(',') : [],
        afterContent: item.newValue != '' ? item.newValue.split(',') : []
      };
    },
    /**
     * @description: 获取品牌
     * @author: 无尘
     */
    getBrandData() {
      const that = this;
      getWxEnterprise({ wxEnterpriseId: that.wxEnterpriseId })
        .then(res => {
          that.brandOptions = res.result || [];
        })
        .catch(function(error) {

        });
    },

    /**
     * @description: 获取列表数据
     * @author: 无尘
     */
    getTableList() {
      const that = this;
      that.loading = true;
      let para = {
        wxEnterpriseId: that.wxEnterpriseId,
        auditType: that.auditType,
        searchType: '0', // 0待审核，1已审核
        search: that.searchValue, // 搜索字段
        pageNum: that.currentPage, // 当前页
        pageSize: that.pageSize, // 一页显示个数
        enterpriseId: that.filterBrand // 品牌
      };
      getReview(para)
        .then(res => {
          that.loading = false;
          that.tableData = res.result.result || [];
          that.total = res.result.totalCount;
        })
        .catch(function(error) {
          that.loading = false;
        });
    }
  }
};
</script>
<style lang="less" scoped>
.w-344 {
  width: 344px;
}
.w-m-100 {
  min-width: 100px;
}
.line-26 {
  line-height: 26px;
}
.el-select {
  vertical-align: middle;
}
/* flex */

.flex {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
}

.flex-1 {
  -webkit-box-flex: 1;
  -webkit-flex: 1;
  -ms-flex: 1;
  flex: 1;
}

.flex-column {
  -webkit-flex-direction: column;
  -moz-flex-direction: column;
  -ms-flex-direction: column;
  -o-flex-direction: column;
  flex-direction: column;
}

.flex-row {
  -webkit-flex-direction: row;
  -moz-flex-direction: row;
  -ms-flex-direction: row;
  -o-flex-direction: row;
  flex-direction: row;
}

.flex-align-center {
  -webkit-box-align: center;
  -webkit-align-items: center;
  -ms-flex-align: center;
  align-items: center;
}

.flex-pack-center {
  -webkit-box-pack: center;
  -webkit-justify-content: center;
  -ms-flex-pack: center;
  justify-content: center;
}

.flex-wrap {
  -webkit-flex-wrap: wrap;
  -moz-flex-wrap: wrap;
  -ms-flex-wrap: wrap;
  -o-flex-wrap: wrap;
  flex-wrap: wrap;
}

.flex-space-between {
  -webkit-justify-content: space-between;
  -moz-justify-content: space-between;
  -ms-justify-content: space-between;
  -o-justify-content: space-between;
  justify-content: space-between;
}

.flex-start {
  -webkit-justify-content: flex-start;
  -moz-justify-content: flex-start;
  -ms-justify-content: flex-start;
  -o-justify-content: flex-start;
  justify-content: flex-start;
}

.bg-82c5ff {
  background: #82c5ff;
}

.color-508cee {
  color: #508cee;
}

.color-ff585c {
  color: #ff585c;
}

.font-13 {
  font-size: 13px;
}

.font-14 {
  font-size: 14px;
}

.line-h-18 {
  line-height: 18px;
}

.line-hidden-2 {
  .flex;
  .flex-align-center;
  .flex-start;
  height: 46px;
  overflow: hidden;
  span {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    line-clamp: 2;
    -webkit-box-orient: vertical;
    box-orient: vertical;
    max-height: 46px;
    overflow: hidden;
  }
}

.w-80 {
  width: 80px;
}

.w-130 {
  display: inline-block;
  width: 130px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

.w-168 {
  display: inline-block;
  width: 168px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

.common-wrap__page {
  margin-top: 24px;
}

.text-center {
  text-align: center;
}

.text-right {
  text-align: right;
}
.hide-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.right-content {
  min-height: calc(100% - 126px);
  .right-box {
    background: #fff;
    min-height: 500px;
    padding: 20px;
    .w-280 {
      width: 280px;
    }
    .w-514 {
      width: 514px;
    }
    .m-l-20 {
      margin-left: 20px;
    }
    .m-t-45 {
      margin-top: 45px;
    }
    .reviewed-body-head {
      margin-bottom: 22px;
    }
    .table-head-pic {
      width: 40px;
      height: 40px;
      border-radius: 4px;
      i {
        font-size: 20px;
        color: #e5f3ff;
      }
      img {
        width: 100%;
        height: 100%;
        border-radius: 3px;
      }
    }
    .apply-info {
      margin-left: 15px;
      line-height: 18px;
      span {
        font-size: 14px;
        color: #606266;
        &.font-13 {
          font-size: 13px;
        }
      }
    }
  }
}

.apply-info-detail {
  padding: 4px;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  .apply-info-img {
    width: 40px;
    height: 40px;
    text-align: center;
    i {
      font-size: 106px;
      color: #e5f3ff;
    }
    img {
      width: 100%;
    }
  }
  .apply-info-right {
    padding-left: 10px;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
  }
}

.approve-dialog {
  .el-icon-success {
    display: inline-block;
    vertical-align: middle;
    font-size: 24px;
    color: #67c23a;
  }
  .approve-icon-tip {
    display: inline-block;
    vertical-align: middle;
    margin-left: 6px;
    font-size: 18px;
    color: #303133;
  }
  .approve-tip {
    margin-top: 31px;
    font-size: 14px;
    color: #606266;
  }
  /deep/.el-dialog__body {
    padding-top: 0;
  }
  /deep/.el-dialog__footer {
    border: none;
    padding: 18px 20px 22px 20px;
  }
}

.refuse-dialog {
  .refuse-tip {
    margin-bottom: 20px;
    font-size: 14px;
    color: #606266;
  }
  /deep/.el-dialog__footer {
    border: none;
    /*padding: 18px 20px 22px 20px;*/
  }
  .el-textarea {
    /deep/ .el-textarea__inner {
      font-size: 14px;
      color: #606266;
      background-color: rgba(255, 255, 255, 0.1);
      resize: none;
    }
  }
}
</style>
