<template>
    <div class="app-container">

        <!-- 查询和其他操作 -->
        <div class="filter-container">
            <!--<el-input v-model="listQuery.userId" clearable class="filter-item" style="width: 160px;" placeholder="请输入用户ID" />-->
            <el-input v-model="listQuery.mobile" clearable class="filter-item" style="width: 160px;" placeholder="请输入用户手机" />
            <el-input v-model="listQuery.bookNo" clearable class="filter-item" style="width: 160px;" placeholder="请输入工单号" />
            <el-select class="filter-item" v-model="listQuery.status" placeholder="请选择预检状态" clearable>
                <el-option :value="0" label="未预检" />
                <el-option :value="1" label="已预检" />
            </el-select>
            <el-date-picker v-model="listQuery.timeArray" type="datetimerange" class="filter-item" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions" value-format="yyyy-MM-dd HH:mm:ss" />


             <el-button v-permission="['GET /admin/pre/list']"  class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
            <el-button  class="filter-item" type="primary"  @click="getrunEtl">刷新盒马预检单</el-button>
        </div>

        <!-- 查询结果 -->
        <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>

            <el-table-column align="center" label="品类师名称" prop="servantName" fixed="left" />
            <el-table-column align="center" label="品类师手机" width="135" prop="servantPhone" />
            <el-table-column align="center" label="预检时间" min-width="90" prop="createTime" />
            <el-table-column align="center" label="客户手机" prop="mobile" />
            <el-table-column align="center" label="工单号" min-width="150" prop="bookNo" />
            <el-table-column align="center" label="城市" min-width="150" prop="stationName" >
                 <template slot-scope="scope">
                     <el-tag>{{ scope.row.stationName|filterCity }}</el-tag>
                 </template>
            </el-table-column>
            <el-table-column align="center" label="服务站" min-width="150" prop="stationName" />
           
              
      <el-table-column align="center" label="是否已预检" min-width="90" prop="status">
        <template slot-scope="scope">
             <el-tag type="success">{{ scope.row.status==0?'未预检':'已预检' }}</el-tag>
          <!-- <el-tag type="success">{{ scope.row.status==0?'未处理':scope.row.status==1?'客户接受':'客户未接受' }}</el-tag> -->
        </template>
      </el-table-column>  

            <el-table-column align="center" label="操作" class-name="small-padding fixed-width" fixed="right" width="180">
                <template slot-scope="scope">
                    <el-button v-permission="['GET /admin/pre/detail']" type="primary" size="mini" @click="handleDetail(scope.row)">详情</el-button>
                    <!-- <el-button v-if="scope.row.orderStatus==202||(scope.row.orderStatus==203&&scope.row.actualPrice>scope.row.refundAmount)||scope.row.orderStatus==204" v-permission="['POST /admin/order/refund']" type="primary" size="mini" @click="handleRefund(scope.row)">退款</el-button> -->
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

        <el-dialog :visible.sync="preDialogVisible" title="预检单详情" width="600px">
            
              <div class="book">
                <div style="border-bottom:0.5px dashed #999">
                    <div class="status">{{tempRow.status==0?'未预检':'已预检'}}</div>
                    <div class="bookname">工单号：{{tempRow.bookNo}}</div>
                    <div class="address">服务地址：{{tempRow.stationName}}-{{tempRow.address}}</div>
                    <div class="serviceTime">上门时段：{{tempRow.serviceTime}}</div>
                    <div class="serviceTime" v-if="tempRow.status==1">服务时间：{{tempRow.createTime}}</div>
                    <div class="goodsname">客户名称：{{tempRow.cusName}}</div>
                </div> 
                <!-- 预检项目   -->
                <div class="content" v-for="(item,index1) in preDetail" :key="'a-'+index1">
                    <div class="category">服务项:{{item.categoryName}}</div>
                    <div class="device">
                        {{item.deviceName}}
                        <span v-if="item.positionName">(</span>
                        <span>{{item.positionName}}</span>
                        <span v-if="item.positionName">)</span>
                    </div>

                    <div v-for="(item2,index2) in item.problemsName" :key="'b-'+index2" class="problem">
                        <div class="item">{{item2}}</div>
                    </div>
                      <div class="item" v-if="item.memo">备注:{{item.memo}}</div>

                    <div v-for="(item3,index3) in item.picUrls" :key="'c-'+index3" class="problemimg">
                        <el-image class="img" style="width: 100px; height: 100px" :src="item3" fit="contain" :preview-src-list="item.picUrls">
                        </el-image>
                    </div> 
                </div>
              </div>    
               <center> 
                <el-button @click="preDialogVisible = false">关闭</el-button> 
             </center>
            
        </el-dialog>

    </div>
</template>

<script>
import { listPre, detailOrder,runEtl } from "@/api/pre";
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination
import { formatDate } from "@/utils/date";
import checkPermission from "@/utils/permission"; // 权限判断函数

export default {
    name: "Pre",
    components: { Pagination },
    filters: {
        filterCity(value){
            if(value==null||value.length==0) return ''
            return value.substring(0,2)
        }
    },
    data() {
        return {
            tempRow: {},
            list: [],
            total: 0,
            listLoading: true,
            listQuery: {
                page: 1,
                limit: 20,
                bookNo: undefined,
                mobile: undefined,
                status: undefined,
                timeArray: [],
                sort: "create_time",
                order: "desc",
            },
            preDialogVisible: false,
            preDetail: [],
            orderDetail: {
                order: {},
            },
            rules: {
                refundMoney: [
                    {
                        required: true,
                        message: "请输入退款金额",
                        trigger: "blur",
                    },
                ],
            },
            pickerOptions: {
                shortcuts: [
                    {
                        text: "最近一周",
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(
                                start.getTime() - 3600 * 1000 * 24 * 7
                            );
                            picker.$emit("pick", [start, end]);
                        },
                    },
                    {
                        text: "最近一个月",
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(
                                start.getTime() - 3600 * 1000 * 24 * 30
                            );
                            picker.$emit("pick", [start, end]);
                        },
                    },
                    {
                        text: "最近三个月",
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(
                                start.getTime() - 3600 * 1000 * 24 * 90
                            );
                            picker.$emit("pick", [start, end]);
                        },
                    },
                ],
            },
        };
    },
    computed: {},
    created() {
        this.getList();
    },
    methods: {
        getrunEtl(){ 
             const loading = this.$loading({
                        lock: true,
                        text: '正在加速刷新数据，若失败请过几分钟再刷...',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0, 0, 0, 0.5)'
                    });
              runEtl().then((response) => {
                    loading.close();
                      this.getList();
                   this.$notify.success({
                        title: "成功",
                        message: "刷新成功",
                    });
              }) .catch(response => {
              loading.close();
              this.$notify.error({
                title: "刷新失败",
                message: "失败了，请过几分钟再刷"
              });
            });   
        },
        checkPermission,
        getList() {
            this.listLoading = true;
            if (
                this.listQuery.timeArray &&
                this.listQuery.timeArray.length === 2
            ) {
                this.listQuery.start = this.listQuery.timeArray[0];
                this.listQuery.end = this.listQuery.timeArray[1];
            } else {
                this.listQuery.start = null;
                this.listQuery.end = null;
            }

            listPre(this.listQuery)
                .then((response) => {
                    this.list = response.data.data.list;
                    this.total = response.data.data.total;
                    this.listLoading = false;
                })
                .catch(() => {
                    this.list = [];
                    this.total = 0;
                    this.listLoading = false;
                });
        },
        handleFilter() {
            this.listQuery.page = 1;
            this.getList();
        },
        handleDetail(row) {
            this.tempRow = row;
            detailOrder(row.id).then((response) => {
                this.preDetail = response.data.data.items;
            });
            this.preDialogVisible = true;
        },
        handleDeleteConfirm(row) {
            this.$confirm("订单删除后无法恢复，确定继续删除吗?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                this.handleDelete(row);
            });
        },
        handleDelete(row) {
            deleteOrder({ orderId: row.id })
                .then((response) => {
                    this.$notify.success({
                        title: "成功",
                        message: "订单删除成功",
                    });
                    this.getList();
                })
                .catch((response) => {
                    this.$notify.error({
                        title: "失败",
                        message: response.data.errmsg,
                    });
                });
        },
        handleRefund(row) {
            this.refundForm.orderId = row.id;
            if (row.refundAmount) {
                this.refundForm.refundMoney = (
                    row.actualPrice - row.refundAmount
                ).toFixed(2);
                this.refundAmount = row.refundAmount;
            } else {
                this.refundForm.refundMoney = row.actualPrice;
            }

            this.actualPrice = row.actualPrice;

            this.refundDialogVisible = true;
            this.$nextTick(() => {
                this.$refs["refundForm"].clearValidate();
            });
        },
        confirmRefund() {
            this.$refs["refundForm"].validate((valid) => {
                if (valid) {
                    let balance = (
                        this.actualPrice - this.refundAmount
                    ).toFixed(2);
                    console.log(balance);
                    if (Number(this.refundForm.refundMoney) == 0) {
                        this.$message.warning("申请退款金额不能为零!");
                    } else if (Number(this.refundForm.refundMoney) > balance) {
                        this.$message.warning(
                            "申请退款金额不能大于未退款金额!"
                        );
                    } else {
                        refundOrder(this.refundForm)
                            .then((response) => {
                                this.refundDialogVisible = false;
                                this.$notify.success({
                                    title: "成功",
                                    message: "确认退款成功",
                                });
                                this.getList();
                            })
                            .catch((response) => {
                                this.$notify.error({
                                    title: "失败",
                                    message: response.data.errmsg,
                                });
                            });
                    }
                }
            });
        },
        handleDownload() {
            this.downloadLoading = true;
            import("@/vendor/Export2Excel").then((excel) => {
                const tHeader = [
                    "客户手机",
                    "订单编号",
                    "下单时间",
                    "收货人联系方式",
                    "上门地址",
                    "城市",
                    "上级合伙人",
                    "订单状态",
                    "支付金额",
                    "支付时间",
                ];
                const filterVal = [
                    "customer.tel",
                    "orderSn",
                    "createTime",
                    "mobile",
                    "address",
                    "city",
                    "rCustomer.customerName",
                    "orderStatus",
                    "actualPrice",
                    "payTime",
                ];
                var lists = [];
                if (this.list && this.list.length > 0) {
                    for (let i = 0; i < this.list.length; i++) {
                        var order = this.list[i];
                        order.city = this.cityFilter(order.address);
                        order.orderStatus = statusMap[order.orderStatus];
                        lists.push(order);
                    }
                    console.info(lists);
                }
                excel.export_json_to_excel2(tHeader, lists, filterVal, "订单");
                this.downloadLoading = false;
            });
        },
    },
};
</script>

<style>
.book {
    /* margin: 20px 20px; */
    margin-bottom: 20px;
    /* height: 320px; */
    /* width: 710px; */
    border: 1px solid #999;
    border-radius: 10px;
    display: flex;
    flex-flow: column;
    padding-bottom: 20px;
}

.bookname {
    display: block;
    color: #333;
    line-height: 22px;
    font-size: 25px;
    margin: 20px 20px;
    font-weight: 500;
}

.address {
    display: block;
    color: darkred;
    line-height: 18px;
    font-size: 18px;
    margin: 20px 20px;
}
.serviceTime {
    display: block;
    color: #333;
    line-height:18px;
    font-size: 18px;
    margin: 20px 20px;
    font-weight: 300;
}
.goodsname {
    color: #333;
    line-height: 18px;
    font-size: 18px;
    margin: 20px 20px;
    font-weight: 300;
}
.status {
    height: 35px;
    float: right;
    margin: 10px;
    background-color: #09afff;
    padding: 10px;
    border-radius: 10px;
    color: #fff;
}

.content{
  margin-top: 20px;
  font-size: 18px;
    line-height:20px;
    font-weight: 500;
    margin: 20px;
    color: #333;
}
.category{
  font-size: 18px;
  color: #333;
  font-weight: 500;
}

.device{
  line-height: 28px; 
  font-size: 18px; 
  font-weight: 200;
      color: #09AFFF;
}
.problem{
  display: flex;
  float: left;
  flex-wrap: wrap;
      color: #09AFFF;
}
.problemimg{
 clear: both;
  display: flex; 
  flex-wrap: wrap;
      color: #09AFFF;
}

.item{
  margin: 5px;
  font-size:16px; 
}

.img{ 
  margin: 10px;
  width: 80px;
  height: 80px;
}

/*-------------- */

.detail-container {
    width: 80%;
    padding: 20px 20px 20px 20px;
    margin: 20px auto;
}

.operate-container {
    background: #f2f6fc;
    height: 80px;
    margin: -20px -20px 0;
    line-height: 80px;
}

.operate-button-container {
    float: right;
    margin-right: 20px;
}

.table-layout {
    margin-top: 20px;
    border-left: 1px solid #dcdfe6;
    border-top: 1px solid #dcdfe6;
}

.table-cell {
    height: 60px;
    line-height: 20px;
    border-right: 1px solid #dcdfe6;
    border-bottom: 1px solid #dcdfe6;
    padding: 10px;
    font-size: 14px;
    color: #606266;
    text-align: center;
    white-space: pre-wrap;
    /* overflow: hidden; */
}

.table-cell-title {
    border-right: 1px solid #dcdfe6;
    border-bottom: 1px solid #dcdfe6;
    padding: 10px;
    background: #f2f6fc;
    text-align: center;
    font-size: 14px;
    color: #303133;
}
.el-table th.gutter {
    display: table-cell !important;
}
.color-danger {
    color: #f56c6c;
    font-size: 18px;
}
/* .img-wrapper img{
    width:100px;
    height: 100px;
    object-fit: contain;
  } */
</style>
