<template>
  <div class="app-container">
    <!-- 详情对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="订单信息" name="first">
          <el-form ref="form" :model="form" label-width="80px">
            <el-row>
              <el-col :span="8">
                <el-form-item label="订单编号" >
                  <el-input v-model="form.orderNo" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="顺序号" >
                  <el-input v-model="form.orderNum" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="订单状态" >
                  <el-input v-model="form.state" disabled/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="城市" >
                  <el-input v-model="form.city" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="店铺" >
                  <el-input v-model="form.shopName" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="创建时间" >
                  <el-input v-model="form.createdAt" disabled/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="商品数量" >
                  <el-input v-model="form.goodsNum" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="金额" >
                  <el-input v-model="form.paidAmount" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="付款时间" >
                  <el-input v-model="form.payTime" disabled/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="用户昵称" >
                  <el-input v-model="form.userName" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="用户电话" >
                  <el-input v-model="form.userPhone" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="完成时间" >
                  <el-input v-model="form.finishTime" disabled/>
                </el-form-item>
              </el-col>
            </el-row>           
            <el-table :data="goodsList" @selection-change="handleSelectionChange" >
              <el-table-column label="商品名称" align="center" prop="goodsName" />
              <el-table-column label="缩略图" align="center">
                <template slot-scope="scope">              
                  <div class="image-tmp">
                    <el-image style="width: 100px; height: 100px"  :src="getPicsList(scope.row.pics)" :preview-src-list="getPicsBigList(scope.row.pics)">
                      <div slot="error" class="image-slot"></div>            
                    </el-image>
                  </div>    
                </template>
              </el-table-column>
              <el-table-column label="商品分类" align="center" prop="categoryName" />
              <el-table-column label="原售价" align="center" prop="oriAmount" />
              <el-table-column label="折扣价" align="center" prop="amountShould" />
              <el-table-column label="实付" align="center" prop="realAmount" />
              <el-table-column label="数量" align="center" prop="num" />
              <el-table-column type="selection"  width="55" :selectable="checkSelectable" v-if="selectionTag"/>                
            </el-table>  
          </el-form>
          <div v-show="refundTag" style="margin-top: 20px;" >
            <el-form ref="refundForm" :rules="rules" :model="refundForm" label-width="80px">
              <el-form-item label="退款金额" prop="refundAmount">
                <el-input  v-model="refundForm.refundAmount" style="width:200px;" placeholder="请输入退款金额" disabled/>
              </el-form-item>
              <el-form-item label="处理备注" prop="desc">
                <el-input  v-model="refundForm.desc" type="textarea" placeholder="请输入处理备注"/>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
        <el-tab-pane label="订单日志" name="second">
          <el-table  :data="logList">
            <el-table-column label="状态" align="center" prop="status" />              
            <el-table-column label="操作" align="center" prop="operation" />
            <el-table-column label="时间" align="center" prop="createAt" />
            <el-table-column label="操作人" align="center" prop="operationUser" />
            <el-table-column label="内容" align="center" prop="content" />        
            </el-table>
        </el-tab-pane>
      </el-tabs>      
      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button v-show="!refundTag" type="primary" @click="submitForm">确定</el-button>
        <el-button v-show="refundTag" type="danger" @click="refundSubmit">退款</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getOrder,getLogList,refund } from "@/api/system/order";
import piovince from '@/utils/piovince';
export default {
  name: "OrderDetial",  
  data() {
    var validateRefundAmount = (rule, value, callback) => {    
      var regular=/(^[+]{0,1}([0-9]+)$)|(^[+]{0,1}([0-9]+)[\.]{1}[0-9]{1,2}$)/; //正数 ,小数可有可无，最多2位
      if (value == undefined || value === '') {        
        callback(new Error('不能为空'));
      }else if(!regular.test(value)){    
        callback(new Error('请输入大于0的正数,最多保留2位小数'));     
      }else if(this.amount){
        let refundAmountValue=parseFloat(value);
        let amountValue=parseFloat(this.amount);
        if(refundAmountValue>amountValue){
          callback(new Error('退款金额不能大于实付金额'));
        }else {
          callback();
        }
      }else {
        callback();
      }
    };
    return {
      selectionTag:false,
      refundTag:false,
      piovince,
      // 总条数
      total: 0,
      // 订单表格数据
      refundList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,     
      shopName: null,    
      goodsList:[],
      // 表单参数
      form: {},
      //退款表单
      refundForm: {
        refundAmount:"",
        desc:"",
        orderId:"",
        orderDetailIds:[]
      },
      rules: {
        refundAmount: [
          { required: true,validator: validateRefundAmount,  trigger: 'blur' }
        ],
        desc: [
          { required: true, message: '请输入退款处理', trigger: 'blur' }
        ]
      },
      activeName:"first",
      logList: [],
      ids:[],      
    };
  },
  created() {
   
  },
  methods: {
    checkSelectable(row,index){
      if(row.refundId==null){
        return true;
      }else{
        return false;
      }      
    },
    getProvince(province){
      let list=this.piovince;
      for(let i=0;i<list.length;i++){
        if(list[i].children.length>0){
          let childrenList=list[i].children;
          for(let j=0;j<childrenList.length;j++){
            if(childrenList[j].value == province){
              return childrenList[j].name;
            } 
          }
        }       
      }
    },
    // 取消按钮
    cancel() {
      this.activeName="first";
      this.open = false;    
    },
    /** 提交按钮 */
    submitForm() {
      this.open=false;
      this.activeName="first"     
    },
    formatterState(state){
       if(state == 0){
        return "创建未校验（创建未校验）";
      }else if(state == 1){
        return "未支付（待付款）";
      }else if(state == 2){
        return "已支付（待制作）";
      }else if(state == 3){
        return "支付制作中（制作中）";
      }else if(state == 4){
        return "制作完成未取（待取餐）";
      }else if(state == 5){
        return "取餐中（取餐中）";
      }else if(state == 6){
        return "正常完成（已完成）";
      }else if(state == 7){
       return "待取超时（已完成）";
      }else if(state == 8){
       return "未支付取消（已取消）";
      }else if(state == 9){
        return "支付后制作前取消（已取消）";
      }else if(state == 10){
        return "制作中取消（已取消）";        
      }else if(state == 11){
        return "制作完成取消（已取消）";  
      }else if(state == 12){
        return "退款中（退款中）";  
      }else if(state == 13){
        return "退款失败（退款失败）";  
      }else if(state == 14){
        return "部分退款（部分退款）";  
      }else if(state == 15){
        return "已退款（已退款）";  
      }else if(state == 50){
        return "其他人工干预状态（其他人工干预状态）";  
      }
    },
    handleClick(tab) {
      if(tab.name=="first"){
        this.getOrderDetail(this.orderId);
      }else if(tab.name=="second"){
        this.getLogList();
      }
    },
    /** 查询订单日志列表 */
    getLogList() {
      //this.loading = true;
      getLogList({orderId:this.orderId}).then(response => {
        if(response.code=="200"){
          this.logList = response.data; 
        }
      });
    },
    //退款
    refundClick(row){
      this.selectionTag=true;
      this.refundForm.refundAmount="";
      this.refundForm.desc="";
      this.refundTag=true;
      this.title="退款处理";
      this.open=true;      
      this.goodsList=[];
      this.orderId= row.id; 
      this.amount=row.amount;
      this.getOrderDetail(this.orderId);
    },
    //提交退款
    refundSubmit(){
      this.refundForm.orderId=this.orderId;
      this.refundForm.orderDetailIds=this.ids;  
      this.$refs["refundForm"].validate((valid) => {       
        if (valid) {          
          refund(this.refundForm).then(response => {
            if(response.code="200"){
              this.open=false;
              this.$emit('getList');
            }
          }); 
        }         
      });    
    },
    /** 详情按钮操作 */
    handleUpdate(row) {
      this.selectionTag=false;
      this.refundTag=false;
      this.goodsList=[];
      this.orderId= row.id; 
      this.title="订单信息";
      this.open = true;
      this.getOrderDetail(this.orderId);
    },
    getOrderDetail(id){
      getOrder(id).then(response => {
        if(response.code=="200"){
          this.goodsList=[];
          this.form = response.data;
          this.form.shopName=response.data.shop.name;
          this.form.state=this.formatterState(response.data.state);  
          this.form.city=this.getProvince(response.data.shop.city);        
          if(response.data.orderDetails.length>0){
            let list=response.data.orderDetails;
            for(let i=0;i<list.length;i++){
             this.goodsList.push({"id":list[i].id,"refundId":list[i].refundId,"goodsName":list[i].goods.name,"pics":list[i].goods.pics,
             "categoryName":list[i].goods.categoryName,"oriAmount":list[i].oriAmount,"amountShould":list[i].amountShould,
             "realAmount":list[i].realAmount,"num":list[i].num,"amount":list[i].amount});
            }
          }
        }        
      });
    },
    getPicsList(str){   
      let picObj = JSON.parse(str);  
      return picObj.thumbnail
    },
    getPicsBigList(str){
      let list=[];
      let picObj = JSON.parse(str);  
      list.push(picObj.thumbnail)
      return list;
    },
    handleSelectionChange(selectList){
      let amount=[];
      this.ids=[];
      if(selectList.length>0){
        for(let i=0;i<selectList.length;i++){
          amount.push(selectList[i].realAmount); 
          this.ids.push(selectList[i].id);
        }
        let sum=this.add(amount);
        this.refundForm.refundAmount=sum;
      }else{
        this.refundForm.refundAmount="";
      }
    },
    add(arr){
      let fieldArr=[]
      for(var i=0;i<arr.length;i++){
        var m, field
        try{
          field=arr[i].toString().split(".")[1].length
        }catch(e){
          field=0
        }
        fieldArr.push(field)
      }
      m=Math.pow(10,Math.max(...fieldArr))
      let add=0;
      arr.forEach(function(item) {
        add=add+item*m
      });
      let sum=Math.round(add)/m
      return sum;
    }    
  }
};
</script>
