<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.orderNo" clearable class="filter-item" style="width: 160px;" placeholder="请输入订单号" />
      <el-input v-model="listQuery.phone" clearable class="filter-item" style="width: 160px;" placeholder="请输入下单手机号" />
      <el-select v-model="listQuery.state" style="width: 200px" class="filter-item" placeholder="请选择订单状态" clearable>
        <el-option  :key="0" label="未兑换" :value="0" />
        <el-option  :key="1" label="已兑换" :value="1" />
      </el-select>
      <el-select v-model="listQuery.orderStatus" style="width: 200px" class="filter-item" placeholder="请选择电信卡订单状态" clearable>
        <el-option  :key="0" label="办理成功" :value="0" />
        <el-option  :key="1" label="办理中" :value="1" />
      </el-select>
      <el-select v-model="listQuery.commodityId" style="width: 200px" class="filter-item" placeholder="请选择商品名称" clearable>
        <el-option v-for="(item, index) in dyCommodityList"  :key="item.dyCommodityId" :label="item.dyCommodityName" :value="item.dyCommodityId" />
      </el-select>
      <el-date-picker v-model="listQuery.timeArray" type="daterange" class="filter-item" range-separator="至"
        start-placeholder="下单开始日期" end-placeholder="下单结束日期" :picker-options="pickerOptions" value-format="yyyy-MM-dd" />
      <el-button v-permission="['POST /admin/telecomCardOrder/getPageList']" class="filter-item" type="primary" icon="el-icon-search"
        @click="handleFilter">查找</el-button>

      <el-button v-permission="['POST /admin/telecomCardOrder/create']" class="filter-item" type="primary" icon="el-icon-search"
                 @click="addOrder()">录入订单</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>
      <el-table-column align="center" label="订单编号" width="135" prop="orderNo" fixed="left" />
      <el-table-column align="center" label="下单手机号" prop="phone" />
      <el-table-column align="center" label="收货人姓名" prop="name" />
      <el-table-column align="center" label="收货人身份证号码" prop="idCard" />
      <el-table-column align="center" label="收货人手机号"  prop="contactMobile" />
      <el-table-column align="center" label="收货地址"  width="300px" prop="installedAddress" />
      <el-table-column align="center" label="商品名称" prop="commodityName" />
      <el-table-column align="center" label="套餐名称" prop="telecomCommodityName" />
      <el-table-column align="center" label="状态" prop="state" >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.state==0" type="warning">未兑换</el-tag>
          <el-tag v-if="scope.row.state==1" type="success">已兑换</el-tag>
        </template>
      </el-table-column>>
      <el-table-column align="center" label="下单时间" prop="createTime" :formatter="dateFormat" />
      <el-table-column align="center" label="兑换时间" prop="conversionTime" :formatter="dateFormat" />
      <el-table-column align="center" label="电信订单号" prop="telecomOrderNo"  />
      <el-table-column align="center" label="电信卡订单状态" prop="orderStatus"  >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.orderStatus==0" type="success">办理成功</el-tag>
          <el-tag v-if="scope.row.orderStatus==1" type="warning">办理中</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="物流公司" prop="freightVendor"  />
      <el-table-column align="center" label="物流编号" prop="freightCode"  />
      <el-table-column align="center" label="抖音券码" prop="ticketCode"  />

      <el-table-column align="center" label="操作" fixed="right" width="200">
        <template slot-scope="scope">
<!--          <el-button v-if="scope.row.state == 0" style="margin-bottom:10px " type="primary" size="mini"
                     @click="sendH5(scope.row)">发送H5邀请</el-button>-->
          <el-button v-if="scope.row.state == 0 && scope.row.commodityId!='dxkd' " v-permission="['POST /admin/telecomCardOrder/saveOrder']" style="margin-bottom:10px" type="primary" size="mini"
                     @click="helpCustomerExchange(scope.row)">帮客户兑换</el-button>
          <el-button v-if="scope.row.state == 0" v-permission="['POST /admin/telecomCardOrder/update']" style="margin-bottom:10px" type="primary" size="mini"
                     @click="updateOrder(scope.row)">编辑</el-button>
<!--          <el-button v-if="scope.row.state == 1"  type="primary" size="mini"
                     @click="getState(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="orderDialogVisible" title="订单状态信息" width="800">
      <el-card shadow="never" style="margin-top: 15px">

        <div style="margin-top: 20px">
          <svg-icon icon-class="marker" style="color: #606266" />
          <span class="font-small">订单状态信息</span>
        </div>
        <div class="table-layout">
          <el-row>
            <el-col :span="8" class="table-cell-title">订单编号</el-col>
            <el-col :span="5" class="table-cell-title">订单状态</el-col>
            <el-col :span="5" class="table-cell-title">订单物流公司</el-col>
            <el-col :span="6" class="table-cell-title">订单物流单号</el-col>
          </el-row>
          <el-row>
            <el-col :span="8" class="table-cell">
              {{
                dxOrderStateInfo.orderNo
              }}
            </el-col>
            <el-col :span="5" class="table-cell">
              {{
                dxOrderStateInfo.msg
              }}
            </el-col>
            <el-col :span="5" class="table-cell">
              {{
                dxOrderStateInfo.freightVendor
              }}
            </el-col>
            <el-col :span="6" class="table-cell">
              {{
                dxOrderStateInfo.freightCode
              }}
            </el-col>
          </el-row>
        </div>

        <div style="float: right;padding-top:10px;padding-bottom: 10px ">
          <el-button type="primary" @click="orderDialogVisible = false">确 认</el-button>
        </div>
      </el-card>
    </el-dialog>

    <!-- 添加或修改对话框  -->
    <el-dialog  :visible.sync="dialogFormVisible" :title="updateFlag?'修改订单':'创建订单'">
      <el-form ref="dataForm"  :rules="rules" :model="dataForm" status-icon label-position="left" label-width="100px" style="width: 700px; margin-left:30px;">
        <el-row>
          <el-col :span="12">
            <el-form-item label="抖音订单号" prop="orderNo" style="width: 200px">
              <el-input v-model="dataForm.orderNo" type="text" style="width: 200px;" placeholder="请输入抖音订单号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下单手机号" prop="phone" style="width: 200px">
              <el-input v-model="dataForm.phone" type="text" style="width: 200px;" placeholder="请输入下单手机号"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="商品名称" prop="commodityId">
          <el-select v-model="dataForm.commodityId" clearable @change="selectCommodity" style="width: 550px" class="filter-item" placeholder="请选择状态">
            <el-option v-for="(item, index) in dyCommodityList"  :key="item.dyCommodityId" :label="item.dyCommodityName" :value="item.dyCommodityId" />
          </el-select>
        </el-form-item>

        <el-form-item label="电商卡套餐名称" prop="telecomCommodityId">
          <el-select v-model="dataForm.telecomCommodityId" clearable style="width: 550px" class="filter-item" placeholder="请选择状态">
            <el-option v-for="(item, index) in telecomCommodityList" :key="item.telecomCommodityId" :label="item.telecomCommodityDesc" :value="item.telecomCommodityId" />
          </el-select>
        </el-form-item>

        <el-row>
          <el-col :span="12">
            <el-form-item label="抖音订单状态" prop="state">
              <el-select v-model="dataForm.state" clearable style="width: 200px" class="filter-item" placeholder="请选择状态">
                <el-option :key="0" label="未兑换" :value="0" />
                <el-option :key="1" label="已兑换" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="抖音券码" prop="ticketCode">
                <el-input v-model="dataForm.ticketCode" type="text" style="width: 200px;" placeholder="抖音券码"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false;updateFlag=false">取消</el-button>
        <el-button  v-if="!updateFlag" type="primary" @click="createData">确定</el-button>
        <el-button v-if="updateFlag" type="primary" @click="updateData">保存</el-button>
      </div>
    </el-dialog>


    <!-- 添加或修改对话框  -->
    <el-dialog  :visible.sync="conversionInterestVisible" title="兑换权益">
      <el-form ref="conversionInterestDataForm"  :rules="conversionInterestRules" :model="conversionInterestDataForm" status-icon label-position="left" label-width="100px" style="width: 700px; margin-left:30px;">
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户姓名" prop="name" style="width: 200px">
              <el-input v-model="conversionInterestDataForm.name" type="text" style="width: 200px;" placeholder="请输入客户姓名"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证" prop="idCard" style="width: 200px">
              <el-input v-model="conversionInterestDataForm.idCard" maxlength="18" show-word-limit  type="text" style="width: 200px;" placeholder="请输入身份证"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>

          <el-button  style="margin-bottom: 20px;" v-if="conversionInterestDataForm.number =='' " type="primary" size="mini"
                     @click="selecPhone">点击选号</el-button>

          <el-form-item  v-if="conversionInterestDataForm.number !='' " label="入网手机号" prop="number" style="width: 200px">
            <el-input v-model="conversionInterestDataForm.number" type="text"  style="width: 200px;" disabled/>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="收获地址" prop="area">
            <el-cascader style="width: 550px" :options="areaList" v-model="conversionInterestDataForm.area" ref="cascader1"
                         @change="handleUpdateAreaChange1" clearable placeholder="省市区"></el-cascader>
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="详细地址" prop="installedAddress">
              <el-input v-model="conversionInterestDataForm.installedAddress" type="text" style="width: 200px;" placeholder="请输入详细地址"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="收货电话" prop="contactMobile">
              <el-input v-model="conversionInterestDataForm.contactMobile" maxlength="11" show-word-limit  type="text" style="width: 200px;" placeholder="请输入收货电话"/>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="conversionInterestVisible = false">取消</el-button>
        <el-button  type="primary" @click="createOrder">确定</el-button>
      </div>
    </el-dialog>

    <!-- 手机号码选择  -->
    <el-dialog  :visible.sync="selectPhoneVisible" width="35%" style="height: 600px" title="选择号码">
        <el-row>
          <el-col :span="11" v-for="(item, index) in phoneList" class="phone" @click="selectedNumer(item,index)" ><span @click="selectedNumer(item,index)">{{item}}</span></el-col>
        </el-row>
        <div slot="footer" class="dialog-footer">
          <el-button  type="primary" @click="restPhone">换一批</el-button>
        </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
// import areaJson from "../../areaJson";
import { regionData } from "element-china-area-data";
import {
  create,
  getPageList,
  getCommodity,
  getTelecomCardCommodity,
  selectNumber,
  createOrder,
  sendH5,
  getState,
  update
} from "@/api/order";
import { allChannel } from "@/api/channel";
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination
import { formatDate } from "@/utils/date";
import checkPermission from "@/utils/permission"; // 权限判断函数
import { getToken } from "@/utils/auth";
import {orderBookReassign} from "@/api/orderStorage";
import moment from "moment/moment";

let vm;

const statusMap = {
  reserve: "预约",
  create: "创建",
  reserve_failed: "预约失败",
  cancel: "取消",
  complete: "完成",
  confirm: "确认服务已完成 待核销",
  sing_in: "签单",
  accept: "接单",
};

export default {
  name: "Order",
  components: { Pagination },
  filters: {
    orderStatusFilter(status) {
      return statusMap[status];
    },
    channelsFilter(value) {
      const rs = vm.channels.filter(item => {
        return item.id === value;
      });
      if (rs != null && rs.length > 0) {
        return rs[0].name;
      }
    }
  },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        phone: undefined,
        orderSn: undefined,
        timeArray: [],
        orderStatusArray: '',
        sort: "create_time",
        order: "desc"
      },
      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]);
            }
          }
        ]
      },
      channels: [],
      statusMap,
      orderDialogVisible: false,
      orderDetail: {
        order: {},
        user: {},
        orderGoods: [],
        refundList: []
      },

      importForm: {
        channelId: 1,
        file: undefined,
        filename: undefined
      },

      headers: { "Content-Type": "multipart/form-data" },

      areaList: regionData,
      dataForm:{},
      dialogFormVisible:false,
      dyCommodityList:[],
      telecomCommodityList:[],
      rules: {
        orderNo: [
          { required: true, message: "请输入抖音订单号", trigger: "blur" },
        ],
        phone: [
          { required: true, message: "请输入下单手机号", trigger: "blur" },
        ],
        commodityId: [
          { required: true, message: "请选择商品名称", trigger: "change" },
        ],
        telecomCommodityId: [
          { required: true, message: "请选择套餐！", trigger: "change" },
        ],
        state: [
          { required: true, message: "请选择状态", trigger: "change" },
        ],
      },
      conversionInterestVisible:false,
      conversionInterestDataForm:{
        number:''
      },
      conversionInterestRules:{
        name: [
          { required: true, message: "请输入姓名", trigger: "blur" },
        ],
        idCard: [
          { required: true, message: "请输入身份证号", trigger: "blur" },
        ],
        number: [
          { required: true, message: "请选择号码", trigger: "change" },
        ],
        area: [
          { required: true, message: "请选择收获地址！", trigger: "change" },
        ],
        installedAddress: [
          { required: true, message: "请输入详细地址", trigger: "blur" },
        ],
        contactMobile: [
          { required: true, message: "请输入收获电话", trigger: "blur" },
        ]
      },
      dyOrder:{},
      phoneList:[],
      selectPhoneVisible:false,
      dxOrderStateInfo:{},
      updateFlag:false
    };
  },
  computed: {},
  beforeCreate() {
    vm = this;
  },
  created() {
    this.getList();
    getCommodity().then(res=>{
      this.dyCommodityList=res.data.data;
    }).catch(res=>{

    })
  },
  methods: {
    checkPermission,
    getList() {
      this.listLoading = true;
      if (this.listQuery.timeArray && this.listQuery.timeArray.length === 2) {
        this.listQuery.orderCreateStartTime = this.listQuery.timeArray[0];
        this.listQuery.orderCreateEndTime = this.listQuery.timeArray[1];
      } else {
        this.listQuery.orderCreateStartTime = null;
        this.listQuery.orderCreateEndTime = null;
      }
      getPageList(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;
        });
    },
    formatTime(time) {
      if (time == null || time === "") {
        return "";
      }
      const date = new Date(time);
      return formatDate(date, "yyyy-MM-dd hh:mm:ss");
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleDetail(row) {
      detailOrder(row.id).then(response => {
        this.orderDetail = response.data.data;
      });
      this.orderDialogVisible = true;
    },
    addOrder(){

      this.dialogFormVisible=true;
      this.updateFlag=false;
      this.dataForm={};
    },
    createData(){
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          create(this.dataForm).then(res=>{
            if (res.data.errno == 0) {
              this.$message.success("录入成功");
              this.getList();
              this.dialogFormVisible=false;
            } else {
              this.$message.error(res.data.errmsg);
            }
          }).catch(res=>{
            console.log(res);
            this.$message.error(res.data.errmsg);
          })
        }
      });

    },
    selectCommodity(value){
      console.log(value)
      getTelecomCardCommodity({commodityId:value}).then(res=>{
        this.telecomCommodityList=res.data.data;
      }).catch(res=>{

      })
    },
    dateFormat(row, column) {
      var date = row[column.property];
      if (date == undefined) {
        return "";
      }
      // return moment(date).format("YYYY-MM-DD HH:mm");
      return moment(date).format("YYYY-MM-DD HH:mm:ss");
    },
    sendH5(row){
      let params={phone:row.phone}
      sendH5(params).then(res=>{
        if (res.data.errno == 0) {
          this.$message.success("发送成功");
        } else {
          this.$message.error(res.data.errmsg);
        }
      }).catch(res=>{
        this.$message.error(res.data.errmsg);
      })

    },
    helpCustomerExchange(row){
      this.conversionInterestVisible=true;
      this.dyOrder=row;
      this.conversionInterestDataForm={};
      this.conversionInterestDataForm.number='';
    },
    handleUpdateAreaChange1(value) {
      console.log(value);
      console.log(this.conversionInterestDataForm.area == "");
      let node = this.$refs["cascader1"].getCheckedNodes();
      console.log(node);
      if (node.length > 0) {
        console.log(node[0].path, node[0].pathLabels);
        this.conversionInterestDataForm.areaCode = node[0].path[2];
        this.conversionInterestDataForm.province = node[0].pathLabels[0];
        this.conversionInterestDataForm.city = node[0].pathLabels[1];
        this.conversionInterestDataForm.county = node[0].pathLabels[2];
        if (
          node[0].pathLabels[2] == "市辖区" &&
          node[0].pathLabels[0] != "北京市" &&
          node[0].pathLabels[0] != "上海市" &&
          node[0].pathLabels[0] != "重庆市" &&
          node[0].pathLabels[0] != "天津市"
        ) {
          this.$notify.error({
            title: "请选择具体区域",
          });
          this.conversionInterestDataForm.area = "";
          return false;
        }

        if (node[0].pathLabels[1] == "市辖区") {
          this.conversionInterestDataForm.city = node[0].pathLabels[0];
        }

      }
    },
    selecPhone(){
      let params={
        orderId:this.dyOrder.id
      }
      const loading = this.$loading({
        lock: true,
        text: '加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      selectNumber(params).then(res=>{
        console.log(res)
        if (res.data.errno == 0) {
            this.phoneList=res.data.data
            this.selectPhoneVisible=true;
        } else {
          this.$message.error(res.data.errmsg);
        }
        loading.close();
      }).catch(res=>{
        console.log(res);
        this.$message.error(res.data.errmsg);
        loading.close();
      })
    },
    restPhone(){
      this.selecPhone();
    },
    selectedNumer(phone,index){
      this.$confirm('确定选择该号码吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success'
      }).then(() => {
        this.conversionInterestDataForm.number=phone.replaceAll("-","");
        this.selectPhoneVisible=false;
      }).catch(() => {

      });
    },
    createOrder(){
      console.log(this.conversionInterestDataForm)
      if(this.conversionInterestDataForm.number == ''){
        this.$message.error("请选择入网号码！")
        return
      }
      this.conversionInterestDataForm.orderId=this.dyOrder.id
      this.$refs["conversionInterestDataForm"].validate((valid) => {
        if (valid) {
          createOrder(this.conversionInterestDataForm).then(res=>{
            if (res.data.errno == 0) {
              this.$message.success("兑换成功");
              this.getList();
              this.conversionInterestVisible=false;
            } else {
              this.$message.error(res.data.errmsg);
            }
          }).catch(res=>{
            console.log(res);
            this.$message.error(res.data.errmsg);
          })
        }
      });
    },
    getState(row){
      let params={telecomOrderNo:row.telecomOrderNo}
      getState(params).then(res=>{
        if (res.data.errno == 0) {
          this.dxOrderStateInfo=res.data.data.data
          this.orderDialogVisible=true;
        }else {
          this.$message.error("查询失败")
        }
      }).then(res=>{
        this.$message.error(res.data.errmsg)
      })
    },
    updateOrder(row){
        this.updateFlag=true;
        console.log(row)
        this.dialogFormVisible=true;
        this.selectCommodity(row.commodityId);
        this.dataForm=row;

    },
    updateData(){
      update(this.dataForm).then(res=>{
        if (res.data.errno == 0) {
          this.$message.success("修改成功");
          this.getList();
          this.dialogFormVisible=false;
        } else {
          this.$message.error(res.data.errmsg);
        }
      }).catch(res=>{
        console.log(res);
        this.$message.error(res.data.errmsg);
      })
    }
  },

};
</script>

<style>
.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: 60px;
  border-right: 1px solid #dcdfe6;
  border-bottom: 1px solid #dcdfe6;
  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;
}

.el-dialog .el-cascader {
  width: 400px;
}

.fixed-width .el-button--mini {
  width: auto;
  min-width: 60px;
}
.phone{
  height: 40px;
  border: #0eaefc 1px solid;
  text-align: center;
  margin: 10px;
  line-height: 40px;
  border-radius: 10px;
  font-size: 16px;


}
</style>
