<template>
  <div class="app-container app-container-scheduling" :style="{'--q-height':qHeight}">
    <div class="app-container-query" ref="queryFormBox">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        
        <el-form-item label="订单号">
          <el-input
            v-model="queryParams.orderId"
            placeholder="请输入订单号"
            clearable
            style="width: 240px;"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="团队名称" label-width="100px">
          <el-input
            v-model="queryParams.teamName"
            placeholder="请输入团队名称"
            clearable
            style="width: 240px;"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="还款状态" label-width="100">
          <el-select
            v-model="queryParams.repaymentStatus"
            placeholder="请选择还款状态"
            clearable
            style="width: 100%"
          >
            <el-option label="未还款" value="0" />
            <el-option label="已还款" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button style="margin-left: 10px;" type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <div class="app-container-table-box">
      <el-row :gutter="10" class="mb8">
        <!-- <el-button
          type="primary"
          size="mini"
          icon="el-icon-download"
          v-hasPermi="['groupBuyingMr:groupBuyingMr:excel']"
          @click="handleExport"
          v-loading.fullscreen.lock="handleExportLoading"
          element-loading-text="正在拼命生成数据中..."
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.5)"
        >导出excel</el-button> -->
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
      <div class="app-container-table-info">
        <el-table ref="tables" v-loading="loading" height="100%" :data="dataList" border>
          <el-table-column label="序号" align="center" type="index" width="60"></el-table-column>
          <el-table-column label="订单号" align="center" prop="orderId" width="170" />
          <el-table-column label="团队名称" align="center" prop="teamName" width="170" />
          <el-table-column label="是否其他团队代付" align="center" prop="ifRepay">
            <template slot-scope="scope">
              <span>{{ scope.row.ifRepay == 0 ? '否' : '是' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="代付团队" align="center" prop="repayName">
            <template slot-scope="scope">
              <span>{{ scope.row.ifRepay == 1 ? scope.row.repayName : '' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="支付方式" align="center" prop="payWay">
            <template slot-scope="scope">
              <span v-if="scope.row.payWay == 'corporate' && scope.row.ifTeamCredit === 1">挂账支付</span>
              <dict-tag v-else :options="dict.type.pay_way_type" :value="scope.row.payWay"/>
            </template>
          </el-table-column>
          <el-table-column label="还款状态" align="center" prop="repaymentStatus">
            <template slot-scope="scope">
              <span>{{ scope.row.repaymentStatus == 0 ? '未还款' : '已还款' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="预计还款时间" align="center" prop="repaymentTime" />
          <el-table-column label="挂账金额" align="center" prop="orderPrice" />
          <el-table-column label="创建时间" align="center" prop="createTime" />
          <el-table-column label="操作" align="center" width="100" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="openDetails(scope.row)"
                v-hasPermi="['team:creditRecord:deatil']"
              >详情</el-button>
              <span v-hasPermi="['team:creaditRecord:pingzheng']" style="display: inline-block;">
                <el-button
                  size="mini"
                  type="text"
                  style="margin-left: 10px;"
                  @click="handleCorporatePay(scope.row)"
                >还款凭证</el-button>
              </span>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </div>
    

    <!-- 详情 -->
    <details-dia ref="detailsDia" :dict="dict" @getList="getList"></details-dia>

      <el-dialog
        title="还款凭证"
        :visible.sync="showCorporatePay"
        width="40%"
        @close="handleCorporatePayClose"
        :before-close="handleCorporatePayClose">
        <el-form v-loading="corporatePayLoading" :model="form" :rules="corporatePayRules" ref="ruleForm1" label-width="120px" class="demo-ruleForm">
          <el-form-item label="还款日期" prop="realPayTime">
            <el-date-picker
              v-model="form.realPayTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="还款凭证" prop="photoList">
            <div style="display: flex;flex-wrap: wrap;">
              <div 
              v-for="(item,index) in form.photoList" 
              :key="index"
              style="width: 100px; height: 100px;margin-top: 5px; position: relative;border: 1px solid #999;border-radius: 5px;margin-right: 20px;">
                <el-image 
                  style="width: 100%; height: 100%"
                  :src="item" 
                  :preview-src-list="form.photoList">
                </el-image>
                <span @click="handleRemove(index)" style="position: absolute;top: -15px;right: -15px;color: red;font-size: 24px;z-index: 999;cursor: pointer;">
                  <i class="el-icon-error"></i>
                </span>
              </div>
              <div 
              style="width: 100px; height: 100px;margin-top: 5px;" 
              v-if="!form.photoList||form.photoList.length<15"
              v-loading="actionUrlLoading"
              element-loading-text="上传中..."
              element-loading-spinner="el-icon-loading"
              element-loading-background="rgba(0, 0, 0, 0.8)"
              >
                <el-upload
                  class="avatar-uploader"
                  :action="uploadObj.url"
                  :headers="uploadObj.headers"
                  :show-file-list="false"
                  :before-upload="beforeAvatarUpload"
                  :on-success="handleAvatarSuccess"
                  :on-progress="handleAvatarProgress"
                  :disabled="actionUrlLoading"
                  :on-error="handleAvatarError"
                  >
                  <i class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </div>
              
            </div>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showCorporatePay = false">取 消</el-button>
          <el-button type="primary" :loading="corporatePayLoading" @click="corporatePay">{{ dialogVisibleLoading?'操作中...':'确定' }}</el-button>
        </span>
      </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import auth from '@/plugins/auth'
import { pageList,gotoCorporatePay, downOrderListXls } from '@/api/team/creditRecord';
import detailsDia from "./dialog/details.vue";

import { exportExcel } from '@/utils/exportexcel'
export default {
  name: "CreditRecord",
  dicts: ['agreement_type', 'team_type','order_status_type','pay_way_type'],
  components: { detailsDia },
  data() {
    return {
      qHeight: '0px',
      resizeObserver: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      dataList: null,
      // 弹出层标题
      title: "",

      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      visibleStatus: false,
      newObj: {},
        dialogVisible: false,
        ruleForm: {},
        rules: {
          region: [
            { required: true, message: '请选择打印机', trigger: ['change','blur' ]}
          ],
        },
        dialogVisibleLoading: false,
        showCorporatePay:false,
        form:{
          payOrCredit: '',
          orderId:'',
          photoList:[],
        },
        corporatePayRules: {
          realPayTime: [{ required: true, message: "选择还款日期", trigger: ["change","blur"] }],
          photoList: [{ required: true, message: "请上传凭证", trigger: ["change","blur"] }],
      },
      uploadObj: {
        url: process.env.VUE_APP_UPLOAD_FILE_API + "/upload/single/minio",
        Headers: { Authorization: "Bearer " + getToken() },
      },
      corporatePayLoading:false,

      handleExportLoading: false,
      pagePerformTimeList: [], // 场次列表
      multiPerformDate:false,
      actionUrlLoading: false,
    };
  },
  created() {
    this.getList();
  },
  activated(){
    this.getList();
  },
  mounted() {
    this.resizeObserver = new ResizeObserver(entries => {
      for (let entry of entries) {
        const { width, height } = entry.contentRect;
        this.qHeight = height + 'px'
      }
      if(document.body.clientWidth<765) {
        this.fixed = false
      }else {
        this.fixed = 'left'
      }
    });
    this.resizeObserver.observe(this.$refs.queryFormBox);
  },
  methods: {
    hasPermi(value){
      return auth.hasPermi(value)
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      let params = {...this.addDateRange(this.queryParams, this.dateRange)};
      if(params.id && params.id.length>19) {
        this.$message({
          type: 'error',
          message: '订单号不存在!!!'
        });
        this.loading = false
        return
      }
      if(params.performDate&&params.performDate.length==2){
        params.performDateStart = params.performDate[0];
        params.performDateEnd = params.performDate[1];
      }else {
        params.performDateStart = null
        params.performDateEnd =null
      }
      delete params.performDate;
      pageList(params)
      .then(response => {
          this.dataList = response.data.rows;
          this.total = response.data.total;
          this.loading = false;
      }).catch(()=>{
        this.dataList = [];
        this.total = 0;
        this.loading = false;
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      }
      this.handleQuery();
    },
    /** 详情按钮操作 */
    openDetails(row, type) {
      this.$refs["detailsDia"].openDialog("详情", row, type);
    },
    async handleCorporatePay(row){
      this.actionUrlLoading = false;
      this.showCorporatePay = true;
      this.form.id = row.id;
      let urlList = row.repaymentVoucherUrl.split(',')||[]
      this.$set(this.form,'photoList',urlList)
      this.$set(this.form,'realPayTime',row.realPayTime)
      this.$nextTick(()=>{
        this.$refs.ruleForm1.clearValidate()
      })
    },
        handleCorporatePayClose(){
          this.$set(this.form,'photoList',[])
          this.getList()
          this.corporatePayLoading = false;
          this.showCorporatePay = false;
        },
        /**  提交上传  */
        corporatePay(){
          console.log('form',this.form);
          this.$refs['ruleForm1'].validate((valid) => {
            if (valid) {
              if(this.form.photoList.length<1){
                this.$message.error('请上传凭证');
                return
              }
              this.corporatePayLoading = true;
              const voucherUrl = this.form.photoList.map(item => item).join(",");
              this.form['repaymentVoucherUrl'] = voucherUrl;
              gotoCorporatePay(this.form).then((res)=>{
                this.$message.success(res.msg);
                this.corporatePayLoading = false;
                this.handleCorporatePayClose();
              }).catch((err)=>{
                this.corporatePayLoading = false;
                this.$message.error(err.msg);
              })
            } else {
              console.log('error submit!!');
              return false;
            }
          });
          
        },
    /**
     * 导出报表
     * @date 2022-10-24
     * @returns {any}
     */
     handleExport() {
      this.$confirm('您确定要导出当前查询的数据吗？', '提示', {
        confirmButtonText: '确定 ',
        cancelButtonText: '取消 ',
        type: 'warning'
      })
        .then(() => {
          this.handleExportLoading = true;
          let postMap = {}
          let params = JSON.parse(JSON.stringify(this.queryParams))
          for (let key in params) {
            if(key != 'pageNum' && key != 'pageSize' && key != 'time' && key != 'performDate' && key != 'invoiceTime'){
              postMap[key] = params[key]
            }
          }
          downOrderListXls(postMap)
            .then((res) => {
              exportExcel(res, '团购订单', '.xlsx');
              this.handleExportLoading = false;
            })
            .catch((error) => {
              console.log("error===",error)
              this.handleExportLoading = false;
            });
        })
        .catch(() => {
          this.$message.info('您已取消导出！');
        });
    },
   
    
    /**  上传图片 单张  */
  handleAvatarSuccess(response, file, fileList) {
      console.log("res, file",response, file, fileList)
      this.actionUrlLoading = false
      if(response.code == 200) {
        this.form.photoList.push(response.data.url)
      }
      this.$refs.ruleForm1.validateField('photoList')
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 <= 100;
      let testmsg = file.name.substring(file.name.lastIndexOf('.')+1)
      let typeList = ['png','jepg','jpg','gif']
      const isJPG = typeList.includes(testmsg);
      if (!isJPG) {
        this.$message.error(`上传图片图片只能是 ${typeList} 格式!`);
      }
      if (!isLt2M) {
        this.$message.error('上传图片图片大小不能超过 100MB!');
      }
      return isJPG && isLt2M;
    },
    handleAvatarProgress(){
      this.actionUrlLoading = true
    },
    handleAvatarError() {
      this.actionUrlLoading = false
    },
    handleRemove(index) {
      this.form.photoList.splice(index,1)
      this.$refs.ruleForm1.validateField('photoList')
    },
  },
  beforeDestroy() {
    this.resizeObserver.unobserve(this.$refs.queryFormBox);
    this.resizeObserver.disconnect();
  },
};
</script>
<style lang="scss" scoped>

  .upload-btn {
    width: 100px;
    height: 100px;
    background-color: #fbfdff;
    border: dashed 1px #c0ccda;
    border-radius: 5px;
    i {
      font-size: 30px;
      margin-top: 20px;
    }
    &-text {
      margin-top: -10px;
    }
  }
  .avatar {
    cursor: pointer;
  }
.app-container {
  height: calc( 100vh - 110px );
  box-sizing: border-box;
}
.app-container-query {
  
}
.app-container-table-box {
  height: calc( 100% - var(--q-height) );
  .app-container-table-info {
    height: calc( 100% - 100px );
  }
}

.upload-box {
  ::v-deep .el-upload--picture-card {
    display: none;
  }
} 

::v-deep .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  ::v-deep .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  ::v-deep .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  ::v-deep .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }

  .app-container-scheduling ::v-deep .el-select__tags {
    flex-wrap: inherit !important;
    overflow-x: auto !important;
}
.app-container-scheduling ::v-deep .el-form-item__content {
  position: relative;
}
.app-container-scheduling ::v-deep .el-form-item__content .query_clear{
  position: absolute;
  top: -15px;
  right: -10px;
  display: none;
  cursor: pointer;
  z-index: 99;
}
.app-container-scheduling ::v-deep .el-form-item__content:hover .query_clear {
  display: block;
}
</style>
