<template>
    <div class="p_all_20 bigbiv">
        <div class="titPart">
            <div class="left">售后详情</div>
        </div>
      <el-tabs v-model="activeName" @tab-click="handleClick(activeName)" v-if="activeName">
        <el-tab-pane label="当前售后" name="0"></el-tab-pane>
        <el-tab-pane label="历史售后" name="1"></el-tab-pane>
      </el-tabs>
        <section class="bigwrap" v-loading="loading">
             <div v-if="detailsInfo.status == 3" class="finish">
                <div class="title">{{ finishData.title }}</div>
                <div>{{ finishData.subTitle }}</div>
                <div>{{ detailsInfo.endDate }}</div>
            </div>
            <el-steps class="stepsbox" :active="moveTypeSteps" align-center
                finish-status="success" v-if="![3,4].includes(detailsInfo.type)">
                <el-step
                    v-for="(item, index) in afterSalesStatus"
                    :key="index"
                    :title="item.name"
                    :description="item.desc"
                />

            </el-steps>
            <div class="contentBig">
                <!-- 0-商家待确认 1-商家待处理 2-买家待确认 3-售后已完成 4-售后未完成 5-售后已撤销", -->
                <div class="tipsbox" v-if="[0,1].includes(detailsInfo.status)">
                    <p>{{getStatusTip(detailsInfo.status)}}</p>
                    <p class="txtp">
                        <el-button v-loading="actionLoading" type="primary" size="mini" @click="onStatusAction">
                            {{getStatusBtn(detailsInfo.status)}}
                        </el-button>
                    </p>
                </div>
                <!-- info -->
                <div class="infobig">
                    <div class="portRight">
                        <div class="titPart">
                            <div class="left">工单信息</div>
                        </div>
                        <ul class="ulbox ulbox2">
                            <li>
                                <span class="s1">售后编号：</span>
                                <span class="s2">{{detailsInfo.afterSalesCode}}</span>
                            </li>
                            <li>
                                <span class="s1">发起人：</span>
                                <span class="s2">{{detailsInfo.initUserName}}</span>
                            </li>
                            <li>
                                <span class="s1">发起日期：</span>
                                <span class="s2">{{detailsInfo.createDate}}</span>
                            </li>
                            <li>
                                <span class="s1">联系电话：</span>
                                <span class="s2">{{detailsInfo.phone}}</span>
                            </li>
                            <li>
                                <span class="s1">售后类型：</span>
                                <span class="s2">{{detailsInfo.afterSalesType}}</span>
                            </li>
                            <li>
                                <span class="s1">售后原因：</span>
                                <span class="s2">{{detailsInfo.reason}}</span>
                            </li>
                            <li>
                                <span class="s1">售后说明：</span>
                                <span class="s2">{{detailsInfo.buyerExplain}}</span>
                            </li>
                        </ul>
                        <template>
                            <div class="infoImg">
                                <div class="imgdiv">
                                    <img :src="detailsInfo.goodsImg" alt="">
                                </div>
                                <div class="textdiv">
                                    <p class="name f_14 ellipsis_2">{{detailsInfo.goodsInfo}}</p>
                                    <p class="pp">sku型号：{{detailsInfo.conner?detailsInfo.conner.model:''}}</p>
                                    <p class="pp">规格：{{detailsInfo.conner?detailsInfo.conner.spec:''}}</p>
                                    <!-- <p class="pp">结算价：¥{{detailsInfo.supplyPrice}}</p> -->
                                    <p class="pp">数量：{{detailsInfo.num}}</p>
                                </div>
                            </div>
                        </template>
                        <ul class="ulbox ulbox1 m_t_10">
                            <!-- <li>
                                <span class="s1">品牌名称：</span>
                                <span class="s2">{{detailsInfo.brandName}}</span>
                            </li> -->
                            <li>
                                <span class="s1">订单编号：</span>
                                <span class="s2">{{detailsInfo.orderCode}}</span>
                            </li>
                        </ul>

                        <template>
                            <div class="titPart titTop0">
                                <div class="left">补发配件地址</div>
                            </div>
                            <ul class="ulbox ulbox3">
                                <li>
                                    <span class="s1">收货人：</span>
                                    <span class="s2">{{detailsInfo.receiver}}</span>
                                </li>
                                <li>
                                    <span class="s1">收货电话：</span>
                                    <span class="s2">{{detailsInfo.receivingPhone}}</span>
                                </li>
                                <li>
                                    <span class="s1">收货地址：</span>
                                    <span class="s2">{{detailsInfo.address}}</span>
                                </li>
                            </ul>
                        </template>
                        <div class="titPart">
                            <div class="left">
                                备注
                                <i class="el-icon-edit-outline" style="color: #f60;cursor: pointer;" @click="onShowRemake"/>
                            </div>
                            <div class="right">仅商家可见</div>
                        </div>
                        <p class="remark" v-if="detailsInfo.remake" @click="onShowRemake">{{detailsInfo.remake}}</p>
                        <p v-else style="color: #515151" @click="onShowRemake">暂无备注，点击编辑</p>
                    </div>
                    <div class="portLeft">
                        <div class="titPart">
                            <div class="left">协商记录</div>
                        </div>
                         <div class="overflowAuto" v-if="detailsInfo.records">
                            <div class="timeStatus" v-for="item in detailsInfo.records">
                                <div class="userItem">
                                    <img class="imgUser" :src="getHead(item.role)" alt="">
                                    <div class="rightdiv m_l_10">
                                        <p class="p1">{{item.who}}<span class="p_l_20">{{item.time}}</span></p>
                                        <p class="p2" v-if="item.action"><span class="f_c_f60">{{item.action}}：</span>{{item.status}}</p>
                                        <p class="p2"><span v-if="item.tip">{{item.tip}}：</span>{{item.reason}}</p>
                                    </div>
                                </div>
                                <div class="imgShow" v-if="item.proof">
                                    <div style="position: relative;display: inline-block;"
                                        v-for="(mItem, index) in item.media">
                                        <el-image
                                            class="elImageStyle"
                                            :src="mItem.thumb"
                                            fit="contain"
                                            @click="openGallery(item.media, index)">
                                        </el-image>
                                        <i v-if="mItem.type == 'video'" class="el-icon-video-play" color="#000"
                                            style="position: absolute;left: 5px;bottom: 5px;"/>
                                    </div>
                                </div>
                            </div>
                         </div>
                    </div>
                </div>
            </div>
        </section>
        <el-dialog title="备注" :visible.sync="remake.show" width="500px" v-loading="remakeLoading">
            <el-form :model="remake" :rules="rules2" ref="remake" >
                <el-form-item prop="value">
                    <el-input
                        v-model="remake.value"
                        type="textarea"
                        :rows="5"
                        show-word-limit
                        maxlength="150"
                        placeholder="请输入备注" />
                </el-form-item>
            </el-form>
            <span slot="footer">
                <el-button @click="remake.show = false">取 消</el-button>
                <el-button type="primary" @click="onRemake">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog title="处理售后" :visible.sync="deal.show" width="600px" v-loading="actionLoading">
            <el-form :model="deal" :rules="rules" ref="deal" label-position="top">
                <el-form-item label="商家说明" prop="sellerExplain">
                    <el-input
                        v-model="deal.sellerExplain"
                        type="textarea"
                        :rows="4"
                        show-word-limit
                        maxlength="300"
                        placeholder="请输入商家说明" />
                </el-form-item>
                <el-form-item label="上传凭证" prop="sellerProof">
                    <el-input v-show="false" v-model="deal.sellerProof" />
                    <uploadImg ref="uploadImgRef" :isMultiple="true" :limitNum="12" :hideLength="12" @uploadResult="uploadResult" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="t_center">
                <el-button type="primary" @click="onDeal">确定处理</el-button>
                <div class="f_c_secondary_text m_t_20">注：确认处理后，此售后工单状态则改变，无法再次修改</div>
            </div>
        </el-dialog>
        <LightBox
            ref="lightbox"
            :media="media"
            :showLightBox="false"
            :interfaceHideTime="9999999999999"
            @onClosed="closeLightBox"
        />
    </div>
</template>
<script>
import uploadImg from "@/components/common/uploadImg"
import { _countTimer,_saveStorage, _getStorage, _addTimer } from "@/utils/utils";
import saleMixin from './modules/saleMixin'
import LightBox from 'vue-it-bigger'
import('vue-it-bigger/dist/vue-it-bigger.min.css')
export default {
    name:'saledetails',
    mixins:[saleMixin],
    components: {
        uploadImg,
        LightBox
    },
    computed:{
        moveTypeSteps(){
            var active = -1
            this.afterSalesStatus.forEach((item, index) => {
                if (this.detailsInfo.status == item.status) {
                    active = index
                }
            })
            return active
        },
        finishData () {
            var data = {}
            if (this.detailsInfo.type == 1) {
                data.title = '售后已完成'
                data.subTitle = '您的十分满意，让商家更有动力~'
            } else if (this.detailsInfo.type == 2) {
                data.title = '售后未完成'
                data.subTitle = '很抱歉，商家没能解决您的问题。'
            } else if ([3,4].includes(this.detailsInfo.type)) {
                data.title = '售后已撤销'
                data.subTitle = this.detailsInfo.type == 3?'发起人撤销售后申请':'平台介入撤销售后申请'
            }
            return data
        }
    },
    data(){
        return {
          activeName:null,
            countdownText:'',
            timer: "",
            baseType:1,
            searchParam: {
                id:''
            },
            detailsInfo:{},
            paramsCompalin:{
                "id": "",//售后id
                "sellerExplain": "",//文本说明
                "sellerProof": ""//上传凭证
            },
            statusTipList: [
                {key: 0, label: '当前的订单状态：买家已成功发起，待商家确认', btn: '确定售后'},
                {key: 1, label: '当前的订单状态：买家已成功发起，待商家确认', btn: '处理售后'},
            ],
            historyList:[],
            hisInit:true,
            rules:{
                sellerExplain: [{ required: true, message: '不能为空', trigger: "change" }],
            },
            loading:false,
            afterSalesStatus:[],
            actionLoading: false,
            deal: {
                show: false,
                sellerExplain: '',
                sellerProof: ''
            },
            rules: {
                sellerExplain: [
                    { required: true, message: '请输入商家说明', trigger: 'change' }
                ],
                sellerProof: [
                    { required: true, message: '请上传凭证', trigger: 'change' }
                ],
            },
            remakeLoading: false,
            remake: {
                show: false,
                value: ''
            },
            rules2: {
                value: [
                    { required: true, message: '请输入备注', trigger: 'change' }
                ],
            },
            media: [],
            headList: {
                0: this.ImgServerUrl + 'aftersale/aftersale_head0.png',
                1: this.ImgServerUrl + 'aftersale/aftersale_head1.png',
                2: this.ImgServerUrl + 'aftersale/aftersale_head2.png'
            }
        }
    },
    mounted(){
        if(this.$route.query.id){
            this.searchParam.id = this.$route.query.id
            this.paramsCompalin.id = this.$route.query.id
            this.getInfo()
        }
    },
    methods:{
      handleClick(e){
        this.getInfo(e)
      },
     uploadResult(res){
        this.paramsCompalin.sellerProof = res?res:''
     },
        getInfo(type=4) {
            const videoReg = /(\.avi)|(\.rmvb)|(\.rm)|(\.asf)|(\.divx)|(\.mpg)|(\.mpeg)|(\.mpe)|(\.wmv)|(\.mp4)|(\.mkv)|(\.vob)/
            const videoThumb = '?x-oss-process=video/snapshot,t_200,f_jpg,m_fast'
            let { brandId } = _getStorage('info');
            var params = this.searchParam;
            params.brandId = brandId;
            let apiurl= '/order/afterSalesV2'
            this.loading =true
            this.$axios.get(apiurl,{
                params
            }).then((res) => {
              let {code,message,msg} =res.data
              if(code==200){
                let data1 = res.data.data
                let data = null
                if(data1.newAfterSales){
                  this.activeName='0'
                  data=data1.newAfterSales
                }else {
                  data=data1.oldAfterSales
                }
                if(type==0){
                  this.activeName='0'
                  data=data1.newAfterSales
                }else if(type==1) {
                  this.activeName='1'
                  data=data1.oldAfterSales
                }
                console.log(data);
                if (data.records && data.records.length > 0) {
                    data.records = data.records.map(item => {
                        return {
                            ...item,
                            media: item.proof?item.proof.split(',').map(mediaUrl => {
                                if (videoReg.test(mediaUrl)) {
                                    return {
                                        type: 'video',
                                        thumb: mediaUrl + videoThumb,
                                        sources: [{ src: mediaUrl }],
                                        width: 800, // Required
                                        height: 600, // Required
                                        autoplay: true
                                    }
                                } else {
                                    return { thumb: mediaUrl, src: mediaUrl }
                                }
                            }):[]
                        }
                    }).reverse()
                  }
                this.detailsInfo = data
                this.afterSalesStatus = data.afterSalesStatus && data.afterSalesStatus.length>0 ?data.afterSalesStatus:[]

              }else{
                this.$message.error(message || msg);
              }

            }).catch(() => {
                this.$message.error('服务器异常');
            }).finally(()=>{
              this.loading =false
            })
        },

        onSave(formName) {
          let params = this.paramsCompalin;

          this.$refs[formName].validate(valid => {
            if (valid) {
              this.$axios.post('/order/editAfterSalesBySupplier', params).then(res => {
                let { code, data, msg,message} = res.data;
                if (code == 200) {
                  this.$message.success(msg || message);
                  this.$router.go(0)
                } else {
                  this.$message.error(msg || message);
                }
              });
            } else {
              return false;
            }
          });
        },
        openGallery (media, index) {
            this.media = media
            this.$refs.lightbox.showImage(index)
        },
        getStatusTip(key) {
            const item = this.statusTipList.find(item => item.key == key)
            return item?item.label:''
        },
        getStatusBtn(key) {
            const item = this.statusTipList.find(item => item.key == key)
            return item?item.btn:''
        },
        onStatusAction () {
            if (this.detailsInfo.status == 0) {
                this.$confirm('确认售后工单？', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.onConfirmAfterSales()
                })
            } else if (this.detailsInfo.status == 1) {
                this.onShowDeal()
            }
        },
        onConfirmAfterSales () {
            if (this.actionLoading) return
            this.actionLoading = true
            let { brandId } = _getStorage('info');
            let apiurl= '/order/confirmAfterSales'
            this.$axios.post(apiurl,{
                id: this.detailsInfo.id,
                brandId
            }).then((res) => {
                let {code,data,message,msg} =res.data
                if(code==200){
                    this.getInfo()
                    this.$message.success('已确认售后工单');
                } else{
                    this.$message.error(message || msg);
                }
            }).catch(() => {
                this.$message.error('服务器异常');
            }).finally(() => {
                this.actionLoading =false
            })
        },
        closeLightBox() {
            document.querySelector('body').style.overflow = 'unset'
        },
        onShowDeal () {
            this.deal.sellerProof = ''
            this.deal.sellerExplain = ''
            this.deal.show = true
            this.$refs.deal.clearValidate();
            this.$nextTick(function(){
                this.$refs.uploadImgRef.imgsJson['supMainImgs'] = []
            })
        },
        uploadResult(res){
            this.deal.sellerProof = res?res:''
        },
        onDeal() {
            this.$refs.deal.validate(valid => {
                if (valid) {
                    if (this.actionLoading) return
                    this.actionLoading = true
                    let { brandId } = _getStorage('info');
                    let apiurl= '/order/editAfterSalesBySupplier'
                    this.$axios.post(apiurl,{
                        id: this.detailsInfo.id,
                        brandId,
                        sellerExplain: this.deal.sellerExplain,
                        sellerProof: this.deal.sellerProof
                    }).then((res) => {
                    let {code,data,message,msg} =res.data
                    if(code==200){
                        this.deal.show = false
                        this.getInfo()
                    } else{
                        this.$message.error(message || msg);
                    }
                    }).catch(() => {
                        this.$message.error('服务器异常');
                    }).finally(() => {
                        this.actionLoading =false
                    })
                }
            })
        },
        onShowRemake () {
            this.remake.value = this.detailsInfo.remake
            if (this.$refs.remake) {
                this.$refs.remake.clearValidate();
            }
            this.remake.show = true
        },
        onRemake () {
            this.$refs.remake.validate(valid => {
                if (valid) {
                    if (this.remakeLoading) return
                    this.remakeLoading = true
                    let { brandId } = _getStorage('info');
                    let apiurl= '/order/editRemake'
                    this.$axios.post(apiurl,{
                        id: this.detailsInfo.id,
                        remake: this.remake.value,
                        brandId
                    }).then((res) => {
                        let {code,data,message,msg} =res.data
                        if(code==200){
                            this.remake.show = false
                            this.detailsInfo.remake = this.remake.value
                            this.$message.success('修改备注成功');
                        } else{
                            this.$message.error(message || msg);
                        }
                    }).catch(() => {
                        this.$message.error('服务器异常');
                    }).finally(() => {
                        this.remakeLoading =false
                    })
                }
            })
        },
        getHead(role) {
            return this.headList[role]
        }
    },

  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer); //在Vue实例销毁前，清除定时器
    }
  }
}
</script>
<style lang="scss" scoped>
.imgsizeCom >>>.el-upload--picture-card{
    height: 100px;
    width: 100px;
    line-height: 100px;
    margin-bottom: 0;
}
.imgsizeCom >>>.el-upload-list--picture-card .el-upload-list__item{
    height: 100px;
    width: 100px;
    line-height: 100px;
    margin-bottom: 0;
}
/deep/ .el-image-viewer__close{
    color: #fff;
}
>>>.el-tabs__item.is-disabled{
    color: '';
}
>>>.el-tabs__item.is-active {
    color: #FF6800;
}
>>>.el-input.is-disabled .el-input__inner{
    color: #666;
}
.remark{
    word-break: break-all;
    line-height: 22px;
    font-size: 12px;
}
.elImageStyle{
    border: 1px solid #e2e2e2;
    padding: 2px;
    width: 100px; height: 100px; margin-right:10px;
}
.bigbiv{
    box-sizing: border-box;
    padding-top: 0px;
}
    .bigwrap{
        margin-top: 20px;
        /deep/ .el-steps{
            .el-step__title{
                font-size: 14px;
            }
            .el-step__head.is-success{
                color: #f60;
                border-color: #f60;
                .el-step__line{
                    background-color: #f60;
                }
                .el-step__icon-inner{
                    display: none;
                }
                .el-step__icon{
                    background-image: url("~@/assets/img/sale/set3.png");
                    background-size: 100% 100%;
                }
            }
            .statusEnd{
                .el-step__head .el-step__icon{
                    background-image: url("~@/assets/img/sale/set4.png") !important;
                    background-size: 100% 100%;
                }
            }
            .el-step__title.is-success{
                color: #f60;
                font-weight: bold;
            }
            .el-step__description.is-success{
                color: #333;
            }
            // 33
            .el-step__head.is-process{
                border-color: #dedede;
                // border-color: #f60;
                .el-step__icon-inner{
                    display: none;
                }
                .el-step__icon{
                    background-image: url("~@/assets/img/sale/set2.png");
                    background-size: 100% 100%;
                }
            }
            .el-step__head.is-wait{
                .el-step__icon-inner{
                    display: none;
                }
                .el-step__icon{
                    background-image: url("~@/assets/img/sale/set1.png");
                    background-size: 100% 100%;
                }
            }
            .el-step__icon{
                width: 20px;
                height: 20px;
            }

            .el-step__icon.is-text{
                border: none;
            }
        }
    }
    .contentBig{
        .tipsbox{
            margin-top: 15px;
            padding: 15px;
            border:1px solid #FE6501;
            background-color: #FFEFE5;
            min-height: 50px;
            margin-bottom: 15px;
            .tit{
                margin-bottom: 10px;
            }
            .txtp{
                margin-top: 10px;
            }
        }
    }
    .titPart{
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 45px;
        font-size: 14px;
        border-bottom: 1px solid rgb(230, 230, 230);
        margin-bottom: 10px;
        color: #333;
        .left{
            font-weight: bold;
            font-size: 14px;
            border-left: 3px solid #ff6600;
            padding-left: 6px;
        }
        .right {
            font-size: 12px;
            font-weight: normal;
            color: #515151;
        }
    }
    .infobig{
        display: flex;
        border:1px solid #e1e1e1;
        min-height: 800px;
        padding: 20px;
        padding-top: 0;
        font-size: 14px;
        .titTop0{
            border-bottom: 0;
            margin-bottom: 0;
            .left{
                border-left: 0;
                padding-left: 0
            }
        }
        .portLeft{
            width: 65%;
            box-sizing: border-box;
            padding-left: 20px;
        }
        .complain_platform{
              border-bottom: 1px dashed #e1e1e1;
        }

        .timeStatus{
            padding: 16px 0;
            border-bottom: 1px dashed #e1e1e1;
            font-size: 14px;
            .userItem{
                display: flex;
                align-items: top;
                align-content: center;
            }
            .imgUser{
                width: 42px;
                height: 42px;
            }
            .rightdiv{
                .p1{
                    margin-bottom: 6px;
                    color: #999;
                }
                .p2{
                    line-height: 22px;
                    word-break:break-all;
                }
            }
            .imgShow{
                margin-top: 10px;
            }
        }
        .portRight{
            width: 35%;
            box-sizing: border-box;
            border-right: 1px solid #e1e1e1;
            padding-right: 20px;
            .infoImg{
                display: flex;
                align-items: center;
                margin-top: 10px;
                .imgdiv{
                    width: 100px;
                    height: 100px;
                    min-width: 100px;
                    img{
                        max-width: 100%;
                        max-height: 100%;
                    }
                }
                .textdiv{
                    margin-left: 10px;
                    .name{
                        line-height: 22px;
                    }
                    .pp{
                        color: #666;
                        padding-top: 15px;
                        font-size: 12px;
                    }
                }
            }
            .ulbox{
                border-bottom: 1px solid #e1e1e1;
                padding-bottom: 10px;
                overflow: hidden;
                li{
                    padding: 4px 0;
                    display: flex;
                    align-items: top;
                    max-width: 100%;
                    font-size: 12px;
                    .s1{
                        color: #999;
                        font-size: 12px;
                        min-width: 60px;
                        text-align: right;
                        margin-right: 5px;
                        line-height: 22px;
                    }
                    .s2{
                        line-height: 22px;
                        flex: 1;
                        word-break:break-all
                    }
                }
            }

        }
    }
.finish {
    color: #8b8b8b;
    font-size: 12px;
    line-height: 1.5em;
    .title {
        color: #333;
        font-weight: bold;
        font-size: 18px;
        margin-bottom: 10px;
    }
}
>>>.el-step__description {
    padding: 0 !important;
}
</style>
