<template>
  <div class="app-container">
    <el-card class="box-card">
      <p class="card-header-tip">
        提现状态：<span class="pay-status">{{ payStatusFormatter(withdrawInfo.pay_status) }}</span>
<!--        提现状态：<strong>{{ payStatusFormatter(withdrawInfo.pay_status) }}</strong>-->
        <span>如果您是电子发票，则不用填写快递公司和单号信息，需上传电子发票图片，同时将电子发票发送至电子邮箱，查看</span>
        <span class="checked-email-rule" @click="isViewSendRuleDialog = true">【电子邮箱及发票发送格式】</span>
      </p>

      <div class="main">
        <div class="card-header-title">
          <span class="blue-block blue-block-goods-title"></span>提现信息
        </div>

        <el-row class="row-title">
          <el-col :span="4" class="text-r">提现流水单号</el-col>
          <el-col :span="9" class="text-l">{{ withdrawInfo.sn }}</el-col>
        </el-row>

        <el-row class="row-title">
          <el-col :span="4" class="text-r">提现时间</el-col>
          <el-col :span="9" class="text-l">{{ formatter(withdrawInfo.created_time) }}</el-col>
        </el-row>

        <el-row class="row-title">
          <el-col :span="4" class="text-r">提现金额</el-col>
          <el-col :span="9" class="text-l">{{ withdrawInfo.amount ? withdrawInfo.amount / 100 : 0 }} 元</el-col>
        </el-row>

        <el-row class="row-title">
          <el-col :span="4" class="text-r">手续费</el-col>
          <el-col :span="9" class="text-l">{{ 0 }} 元</el-col>
<!--          <el-col :span="9" class="text-l">{{ withdrawInfo.service_fee ? withdrawInfo.service_fee / 100 : 0 }} 元</el-col>-->
        </el-row>

        <el-row class="row-title">
          <el-col :span="4" class="text-r">实际到账金额</el-col>
          <el-col :span="9" class="text-l">{{ withdrawInfo.real_amount ? withdrawInfo.real_amount / 100 : 0  }} 元</el-col>
        </el-row>

        <el-row class="row-title">
          <el-col :span="4" class="text-r">提现至账户</el-col>
          <el-col :span="9" class="text-l">{{ withdrawInfo.bank_name_all }}</el-col>
        </el-row>

        <el-row class="row-title">
          <el-col :span="4" class="text-r">发票信息</el-col>
          <el-col :span="9" class="text-l">
            <el-link v-if="withdrawInfo.invoice_status == 1" :underline="false" type="primary" @click="viewInvoiceDetails">点击查看发票</el-link>
            <el-link v-else disabled>发票未提交</el-link>
          </el-col>
        </el-row>

        <div class="card-header-title">
          <span class="blue-block blue-block-goods-title"></span>打款备注
        </div>
        <div class="remark-con">
          <p v-if="payRemark">{{ payRemark }}</p>
          <p v-else style="color: #555;">暂无备注</p>
        </div>
      </div>

      <div class="footer-btn">
        <el-button type="primary" @click="exportGoodsDetails" style="margin-right:20px;">导出商品明细</el-button>
        <el-button @click="submitInvoiceAgain" :disabled="isSubmitInvoice">补充发票信息</el-button>
      </div>

    </el-card>

    <!-- 电子发票 规则 -->
    <el-dialog
      title="电子发票发送格式"
      :visible.sync="isViewSendRuleDialog"
      width="40%"
      center
    >
      <div class="view-sendemail-rule">
        <p>您好，如果您是电子发票，请通过邮箱按照以下格式发送：</p>
        <p><span class="span-title">标题：</span>【XXX公司】电子发票</p>
        <p><span class="span-title spe-1">收件人：</span>finanical@stbz.net</p>
        <p><span class="span-title">正文内容：</span>【XXX公司】电子发票</p>
        <p><span class="span-title spe-1">附件：</span>电子发票</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="isViewSendRuleDialog = false" size="small">关 闭</el-button>
      </span>
    </el-dialog>

    <!-- 补充发票 信息 -->
    <el-dialog
      title="补充发票信息"
      :destroy-on-close="true"
      :visible.sync="isAddInvoiceAgainDialog"
      :before-close="cancelUpInvoiceImg"
      width="40%"
      center>
      <el-form ref="addInvoiceForm" :model="addInvoiceForm" :rules="addInvoiceRule" label-width="150px" class="add-invoice-form" size="small">
        <el-form-item label="快递公司：" prop="express_name">
          <el-select v-model="addInvoiceForm.express_name" filterable placeholder="请选择快递公司" style="width: 80%;">
            <el-option
              v-for="item in expressLists"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="快递单号：" prop="express_sn">
          <el-input v-model="addInvoiceForm.express_sn" placeholder="请输入快递单号" style="width: 80%;"></el-input>
        </el-form-item>

        <el-form-item label="发票图片：" prop="invoice_img">
          <el-upload
            class="avatar-uploader"
            action=""
            list-type="picture-card"
            :http-request="uploadInvoiceImg"
            :before-upload="beforeUpInvoiceImg"
            :file-list="invoiceImgList"
            :limit="1"
            :on-exceed="limitCount1"
            :before-remove ="beforeRemoveInvoiceImg"
            :on-remove="removeInvoiceImg"
            :on-preview="handleInvoiceImg"
          >
            <i class="el-icon-plus"></i>

          </el-upload>
          <el-dialog :visible.sync="dialogVisibleInvoiceImg" class="dialog-img-spe">
            <img width="100%" :src="dialogInvoiceImg" alt=""/>
          </el-dialog>
          <div class="textTip">最多上传一张图片，仅限jpg/png格式，大小限制在500kb以内</div>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitInvoice" size="small">确 定</el-button>
        <el-button type="primary" @click="cancelUpInvoiceImg" size="small">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 查看发票 信息 -->
    <el-dialog
      title="发票信息"
      :destroy-on-close="true"
      :visible.sync="isViewInvoiceAgainDialog"
      width="40%"
      center>
      <el-form :model="viewInvoiceForm" label-width="150px" class="add-invoice-form" size="small">
<!--        <el-form-item label="快递公司：" >-->
<!--          <el-input v-model="viewInvoiceForm.express_name" placeholder="请输入快递单号" disabled style="width: 80%;"></el-input>-->
<!--        </el-form-item>-->

        <el-form-item label="快递公司：" prop="express_name">
          <el-select v-model="viewInvoiceForm.express_name" disabled placeholder="请选择快递公司" style="width: 80%;">
            <el-option
              v-for="item in expressLists"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="快递单号：">
          <el-input v-model="viewInvoiceForm.express_sn" placeholder="请输入快递单号" disabled style="width: 80%;"></el-input>
        </el-form-item>

        <el-form-item label="发票图片：">
          <div v-if="viewInvoiceForm.invoice_img">
            <el-image
              style="width: 100px; height: 100px;border:1px solid #eee;"
              :src="viewInvoiceForm.invoice_img"
              :preview-src-list="viewInvoiceForm.invoiceImgList">
            </el-image>
          </div>
<!--          <div class="textTip">最多上传一张图片，仅限jpg/png格式，大小限制在500kb以内</div>-->
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="isViewInvoiceAgainDialog = false" size="small">关 闭</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
  import { getWithdrawlogDetailsData,exportGoodsDetailsData,getExpressListData ,upLoadImg, addInvoiceData } from '@/api/module/bankcard'
  import {dateFormat} from '@/utils'
  export default {
    name: "Wddetails",
    data() {
      let checkPic = (rule, value, callback) => {
        if(this.invoiceImgList.length > 0) {
          callback();
        }else if(this.invoiceImgList.length === 0) {
          callback(new Error("发票图片不能为空"));
        }
      };
      return {
        withdrawId: 0,
        withdrawInfo: {
          pay_status: 0,
          sn: '',
          created_time: 0,
          amount: 0,
          service_fee: 0,
          real_amount: 0,
          bank_name: '',
          bank_branch_name: '',
          bank_card_id: '',
          bank_name_all: '',
          invoice_status: 0,
        },
        payRemark: '', // 打款备注
        // 查看 电子发票发送格式
        isViewSendRuleDialog: false,
        isSubmitInvoice: false, // 是否 补充提交发票

        // 补充发票
        isAddInvoiceAgainDialog: false, // 补充发票信息 对话框
        expressLists: [],
        invoiceImgList: [],// 发票图片 file
        invoiceImgBase64List: [],// 发票图片 base64格式
        addInvoiceForm: {
          express_name: '',
          express_sn: '',
          invoice_img: ''
        },
        addInvoiceRule: {
          express_name: [{required: true,message: '物流公司名称不能为空',trigger: 'change'}],
          express_sn: [{required: true,message: '快递单号不能为空',trigger: 'blur'}],
          invoice_img: [{ required: true, validator: checkPic}]
        },

        dialogVisibleInvoiceImg: false,
        dialogInvoiceImg: '',

        // 查看 发票信息
        isViewInvoiceAgainDialog: false,
        viewInvoiceForm: {
          express_name: '',
          express_sn: '',
          invoice_img: '',
          invoiceImgList: [],
        }
      }
    }, // data end
    created() {
      // 提现记录 id
      this.withdrawId = Number(this.$route.query.withdrawId);
      // 获取 物流公司 列表
      this.getExpressList();
      //  查询 提现记录 详情
      this.getWithdrawlogDetails();
    },
    methods: {
      /** 查询 提现记录 详情 */
      getWithdrawlogDetails() {
        const id = this.withdrawId
        getWithdrawlogDetailsData({id: id}).then(res=> {
          if (res.code == 1 && res.data) {
            if (res.data.withdraw_info) {
              this.withdrawInfo = res.data.withdraw_info;
              // 提现至账户 处理
              if( this.withdrawInfo.bank_card_id ) {
                let strBankcardId = this.withdrawInfo.bank_card_id + '';
                let Forward4 = strBankcardId.substring(0,4)
                let backward4 = strBankcardId.substring(strBankcardId.length-4,strBankcardId.length)
                this.withdrawInfo.bank_name_all = this.withdrawInfo.bank_name + '\u00a0\u00a0' + Forward4 + '****' + backward4;
              }
              // 补充发票信息 按钮 是否可以点击
              this.isSubmitInvoice = this.withdrawInfo.invoice_status == 1 ? true : false;
            }
            // 打款备注
            if(res.data.action_logs && res.data.action_logs.content) {
              this.payRemark = res.data.action_logs.content;
            }
          }
        });
      },

      /** 导出商品明细 */
      exportGoodsDetails() {
        exportGoodsDetailsData( {id: this.withdrawId} ).then(res=> {
          //debugger
          if (res.code == 1) {
            if(res.data) {
              this.$message({type:'success',message:'导出成功'});
              const aLink = document.createElement('a');
              aLink.href = res.data;
              //aLink.download = '订单.xls'; //下载的文件名
              aLink.style.display = 'none';
              document.body.appendChild(aLink);
              aLink.click();
              document.body.removeChild(aLink);
            }else {
              this.$message({type:'warning',message: res.message ? res.message: '导出失败'});
            }
          }else {
            this.$message({type:'error',message: res.message ? res.message: '导出失败'});
          }
        });
      },

      /** 补充发票信息 */
      submitInvoiceAgain() {
        this.isAddInvoiceAgainDialog = true;
      },

      /** 上传 发票图片 数量限制 1  */
      limitCount1(files, fileList) {
        this.$message({message: '最多上传1张图片', type: 'warning'});
      },

      /** 发票图片 各种校验*/
      beforeUpInvoiceImg(file) {
        if (file.type !== "image/png" && file.type !== "image/jpg" && file.type != "image/jpeg") {
          this.$message({
            message: '上传图片格式只支持png/png格式',
            type: "warning"
          });
          return false;
        }
        let isImgSize = (file.size / 1024 ) > 500;
        if (isImgSize) {
          this.$message({
            message: '上传图片大小不能超过500kb',
            type: "warning"
          });
          return false;
        }
      },

      /** 上传 发票 图片 */
      uploadInvoiceImg(param) {
        this.getBase64(param.file).then( res => {
          let result = res.split(",");
          this.Base64img = result[1];
          let data = {"img_data":this.Base64img};
          this.invoiceImgBase64List = [] // 初始化
          upLoadImg(data).then( res=> {
            let urlObj = {'url': ''};
            if(res.data) {
              urlObj.url = res.data.image_url;
              this.invoiceImgList.push(urlObj); // 展示用
              this.addInvoiceForm.invoice_img = res.data.image_url // 字段无用，清除校验有用
              this.invoiceImgBase64List.push( data.img_data );
              this.$message({type:'success',message:'图片上传成功'});
              this.$refs.addInvoiceForm.clearValidate('invoice_img');
            }
          });
        });
      },

      /** 发票 删除前 */
      beforeRemoveInvoiceImg(file) {
        if (file.status === "success") {
          return new Promise((res, rej) => {
            this.$confirm(`是否删除此图片`, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              return res();
            }).catch(() => {
              this.$message({
                type: 'success',
                message: '取消删除!'
              });
              return rej();
            });
          });
        }
      },

      /** 发票图片 删除 */
      removeInvoiceImg(file) {
        if (file.status === "success") {
          for (let i = 0; i < this.invoiceImgList.length; i++) {
            if (file.uid === this.invoiceImgList[i].uid) {
              this.invoiceImgList.splice(i, 1);
              this.invoiceImgBase64List.splice(i, 1);
            }
          }
          this.$message( {type: 'success', message: '删除成功!'} );

          if(this.invoiceImgList.length === 0) {
            this.$refs.addInvoiceForm.validateField('invoice_img')
          }else {
            this.$refs.addInvoiceForm.clearValidate('invoice_img');
          }
        }
      },

      /** 发票图片 预览 */
      handleInvoiceImg(file) {
        this.dialogInvoiceImg = file.url;
        this.dialogVisibleInvoiceImg = true;
      },

      /** 提交 补充的发票信息 */
      submitInvoice() {
        let params = {
          id: '',
          express_company: '',
          express_no: '',
          invoice_img: [],
        }
        this.$refs.addInvoiceForm.validate((valid)=> {
          if (valid) {
            params.id = this.withdrawId;
            //params.express_company = this.addInvoiceForm.express_name;
            params.express_no = this.addInvoiceForm.express_sn;
            params.invoice_img = this.invoiceImgBase64List

            for(let i = 0; i < this.expressLists.length; i++) {
              if(this.addInvoiceForm.express_name == this.expressLists[i].value) {
                params.express_company = this.expressLists[i].label
              }
            }

            addInvoiceData(params).then(res=> {
              if(res.code == 1) {
                this.$message({type:'success',message: '补充发票信息成功'});
                this.isAddInvoiceAgainDialog = false;
                this.resetAddInvoiceForm();
                this.getWithdrawlogDetails();
              }else {
                this.$message({type:'success',message:  res.message ? res.message : '补充发票信息失败' });
              }
            });
          }
        });
      },

      /** 取消 提交 补充的发票信息 */
      cancelUpInvoiceImg() {
        this.resetAddInvoiceForm();
        this.isAddInvoiceAgainDialog = false;
      },

      /** 初始化 补充发票的 表单数据 */
      resetAddInvoiceForm() {
        this.addInvoiceForm.express_name = ''
        this.addInvoiceForm.express_sn = ''
        this.addInvoiceForm.invoice_img = ''
        this.invoiceImgList = []
        this.invoiceImgBase64List = []
      },

      /** 查看 发票详情 */
      viewInvoiceDetails() {
        this.isViewInvoiceAgainDialog = true;
        if( this.withdrawInfo.express_company ) {
          this.viewInvoiceForm.express_name = this.withdrawInfo.express_company
        }
        if( this.withdrawInfo.express_no ) {
          this.viewInvoiceForm.express_sn = this.withdrawInfo.express_no
        }
        if( this.withdrawInfo.invoice_img_arr[0] ) {
          this.viewInvoiceForm.invoice_img = this.withdrawInfo.invoice_img_arr[0]
          this.viewInvoiceForm.invoiceImgList = this.withdrawInfo.invoice_img_arr
        }
      },

      /** 获取 物流公司 列表 */
      getExpressList() {
        getExpressListData().then(res=> {
          if (res.code == 1) {
            this.expressLists = res.data.expressLists
          }
        });
      },

      /** 提现状态 格式 */
      payStatusFormatter(type) {
        let typeMsg = '';
        if(type == 0) {
          typeMsg = '打款中'
        }else if (type == 1) {
          typeMsg = '提现成功'
        }
        return typeMsg
      },
      /** 时间格式化 */
      formatter(time) {
        return dateFormat(time * 1000, 'Y-m-d H:i:s')
      },
      /** 图片 base64 */
      getBase64(file) {
        return new Promise(function (resolve, reject) {
          let reader = new FileReader();
          let imgResult = "";
          reader.readAsDataURL(file);
          reader.onload = function () {
            imgResult = reader.result;
          };
          reader.onerror = function (error) {
            reject(error);
          };
          reader.onloadend = function () {
            resolve(imgResult);
          };
        });
      },
    }// methods end
  }
</script>

<style scoped>
  /deep/ .el-card__body{
    height: 100%;
    overflow: hidden;
  }

  .card-header-tip {
    height: 48px;
    line-height: 48px;
    background: #FFF5ED;
    border: 1px solid #F1914E;
    font-size: 14px;
    font-weight: 400;
    color: #333333;
    padding: 0 15px;
    margin-bottom: 0;
    overflow: hidden;
  }
  .pay-status {
    margin: 0 10px;
    font-size: 16px;
    font-weight: 600;
  }
  .checked-email-rule {
    color: #F1914E;
    cursor: pointer;
  }

  .main {
    height: calc(100% - 130px);
    overflow-y: auto;
  }

  .card-header-title {
    line-height: 24px;
    font-size: 18px;
    color: #000;
    font-weight: bold;
    margin: 20px 0;
  }

  .blue-block {
    display: inline-block;
    width: 5px;
    height: 24px;
    background: #3A84FF;
    margin: 0 9px 0 0;
    border-radius: 2px;
    vertical-align: bottom;
  }

  /* 提现信息 */
  .row-title {
    font-size: 14px;
    color: #333;
  }

  /deep/.el-col {
    border: 1px solid #eee;
    padding: 0 10px;
    height: 45px;
    display: flex;
    align-items: center;
  }

  .text-r {
    justify-content: center;
    background: #F7F8FA;
    align-items: center;
  }
  .text-l {
    justify-content: center;
    align-items: center;
  }

  .view-sendemail-rule {
    margin: 20px 20%;
  }
  .view-sendemail-rule > p{
    line-height: 30px;
  }
  .span-title {
    display: inline-block;
    width: 100px;
    text-align: left;
    font-weight: 500;
  }

  .spe-1 {
    margin-right: 7px;
  }

  .remark-con {
    min-height: 140px;
    width: 70%;
    background: #F7F8FA;
    border: 1px solid #E7E7EB;
    margin: 0 0 20px;
    font-size: 14px;
    padding: 0 20px;
    color: #333333;
  }

  .remark-con > p {
    line-height: 24px;
  }

  .footer-btn {
    width: calc(100% + 40px);
    margin-left: -20px;
    padding-top: 20px;
    height:65px;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    box-shadow: 0 -8px 9px 1px rgba(51, 51, 51, 0.06);
  }

  /* 补充发票 */
  .add-invoice-form {
    margin: 0 40px;
  }
</style>
