<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单号">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入订单号"
          clearable
          style="width: 240px;"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="团队名称" label-width="100px">
        <el-input
          v-model="queryParams.teamName"
          placeholder="请输入团队名称"
          clearable
          style="width: 240px;"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="团队类型">
        <el-select
        v-model="queryParams.teamTypeId"
        placeholder="团队类型"
        clearable
        style="width: 240px"
        >
        <el-option
          v-for="dict in dict.type.team_type"
          :key="dict.value"
          :label="dict.label"
          :value="dict.value"
        />
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态">
        <el-select
          v-model="queryParams.status"
          placeholder="订单状态"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="dict in statusMapList"
            :key="dict.value"
            :label="dict.name"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="支付时间">
        <el-date-picker
          v-model="queryParams.time"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="场次时间">
        <el-date-picker
          style="width: 230px;"
          v-model="queryParams.performDate"
          @change="pagePerformTimeListFun"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="场次">
        <el-select
          v-model="queryParams.performTimeId"
          placeholder="场次"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="dict in pagePerformTimeList"
            :key="dict.id"
            :label="dict.timeSnapshot"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-button
        type="primary"
        size="mini"
        icon="el-icon-download"
        v-hasPermi="['groupBuyingMr:groupBuyingMr:excel']"
        @click="handleExport"
        v-loading.fullscreen.lock="handleExportLoading"
        element-loading-text="正在拼命生成数据中..."
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.5)"
      >导出excel</el-button>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="tables" v-loading="loading" :data="dataList" border>
      <el-table-column label="序号" align="center" type="index" width="60"></el-table-column>
      <el-table-column label="订单号" align="center" prop="id" />
      <el-table-column label="团队名称" align="center" prop="teamName" />
      <el-table-column label="团队类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.team_type" :value="scope.row.teamType"/>
        </template>
      </el-table-column>
      <el-table-column label="联系电话" align="center" prop="teamMobile" />
      <el-table-column label="负责人" align="center" prop="teamContact" />
      <el-table-column label="剧目名称" align="center" prop="performName" />
      <el-table-column label="票务名称" align="center" prop="goodsName" />
      <el-table-column label="座位类型" align="center" prop="seatTypeName" />
      <el-table-column label="场次时间" align="center" prop="performDate" />
      <el-table-column label="场次" width="120" align="center" prop="timeSnapshot">
        <template slot-scope="scope">
          <span>{{ scope.row.timeSnapshot }} <br /> ({{ scope.row.performTimeStart + '-' + scope.row.performTimeEnd }})</span>
        </template>
      </el-table-column>
      <el-table-column label="团购数量" align="center" prop="quantity" />
      <el-table-column label="支付总额" align="center" prop="orderPrice">
        <template slot-scope="scope">
          <span>￥{{ scope.row.orderPrice }}</span>
        </template>
      </el-table-column>
      <el-table-column label="支付方式" align="center" prop="type">
        <template slot-scope="scope">
          <!-- <el-tooltip placement="top">
            <div slot="content">
               <span>{{ payWayList[scope.row.payWay] }}</span>
            </div>
            <span>{{ payWayList[scope.row.payWay] }}</span>
          </el-tooltip> -->
          <span>{{ payWayList[scope.row.payWay] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="支付时间" align="center" prop="payTime" width="160" >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.payTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="type">
        <template slot-scope="scope">
          <span>{{statusList[scope.row.status]}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="100" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="openDetails(scope.row)"
            v-hasPermi="['groupBuyingMr:groupBuyingMr:details']"
          >详情</el-button>
          <el-button
          v-if="scope.row.status===0"
            size="mini"
            type="text"
            @click="handleCorporatePay(scope.row)"
            v-hasPermi="['groupBuyingMr:groupBuyingMr:details']"
          >对公转账</el-button>
          <el-button
              v-if="scope.row.status == 3 || scope.row.status == 7"
              size="mini"
              type="text"
              @click="handleOpen([scope.row])"
              v-hasPermi="['groupBuyingMr:groupBuyingMr:print']"
            >打印小票</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 详情 -->
    <details-dia ref="detailsDia" :dict="dict" @getList="getList"></details-dia>


    <el-dialog
        title="选择小票机"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="小票机" prop="region">
            <el-select v-model="ruleForm.region" placeholder="选择小票机">
              <el-option :label="item.deviceName" :key="item.id" :value="item.id" v-for="(item,index) in printList"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" :loading="dialogVisibleLoading" @click="print(viewerList)">{{ dialogVisibleLoading?'打印中...':'打印' }}</el-button>
        </span>
      </el-dialog>

      <el-dialog
        title="对公信息凭证"
        :visible.sync="showCorporatePay"
        width="50%"
        @close="handleCorporatePayClose"
        :before-close="handleCorporatePayClose">
        <el-form :model="ruleForm" :rules="corporatePayRules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="凭证上传" prop="photoList" required>
            <el-upload
                ref="upload"
                :action="uploadObj.url"
                :headers="uploadObj.headers"
                accept=".jpg,.png"
                :on-success="handlePhotoListSuccess"
                :before-upload="beforeAvatarUpload"
                list-type="picture-card"
                :file-list="form.photoList"
                :on-remove="handleRemove"
                :limit="2"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
          </el-form-item>
          <el-form-item label="备注">
            <el-input placeholder="请备注" type="textarea" maxlength="300" show-word-limit v-model="form.corporate.remark"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showCorporatePay = false">取 消</el-button>
          <el-button type="primary" :loading="corporatePayLoading" @click="corporatePay">{{ dialogVisibleLoading?'操作中...':'确定' }}</el-button>
        </span>
      </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { pageList,gotoCorporatePay, downOrderListXls } from '@/api/order/groupBuyingMr'
import detailsDia from "./dialog/details.vue";

import { printApi } from '@/api/order/orderMr'
import { pageList as getPrintListApi } from "@/api/device/pda";
import { pagePerformTimeList } from "@/api/schedulingMr/schedulingMr"
import { exportExcel } from '@/utils/exportexcel'

const https = require('https');
const axios = require('axios');
export default {
  name: "agreement",
  dicts: ['agreement_type', 'team_type'],
  components: { detailsDia },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      dataList: null,
      // 弹出层标题
      title: "",

      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      statusList: {
        0: '待支付',
        2: '超时取消',
        3: '待使用',
        4: '退款中',
        5: '己退款',
        6: '退款失败',
        7: '己使用',
        8: '己超期',
        9: '关闭',
      },
      statusMapList: [
        {id: 1, name: '待支付', value: 0},
        {id: 2, name: '超时取消', value: 2},
        {id: 3, name: '待使用', value: 3},
        {id: 4, name: '退款中', value: 4},
        {id: 5, name: '己退款', value: 5},
        {id: 6, name: '退款失败', value: 6},
        {id: 7, name: '己使用', value: 7},
        {id: 8, name: '己超期', value: 8},
        {id: 9, name: '关闭', value: 9},
      ],
      payList: {
        0: '未支付',
        1: '已支付',
        2: '支付中',
        3: '支付失败',
        4: '支付退款',
      },
      payWayList: {
        'cahsh': '现金',
        'wecaht.applet': '微信小程序支付',
        'alipay': '支付宝OTA',
        'wecaht.h5': '微信公众号支付',
        'meituan': '美团支付',
        'corporate': '对公支付',
      },
      sourceList: {
        1: '小程序',
        2: '公众号',
        3: '美团',
        4: '携程',
        5: '团购',
      },
      sourceMapList: [
        {id: 1, name: '小程序', value: 1},
        {id: 2, name: '公众号', value: 2},
        {id: 3, name: '美团', value: 3},
        {id: 4, name: '携程', value: 4},
        {id: 5, name: '团购', value: 5},
      ],
      visibleStatus: false,
      newObj: {},
      visibleType: '',


      viewerList: [],
        printList: [],
        dialogVisible: false,
        ruleForm: {},
        rules: {
          region: [
            { required: true, message: '请选择打印机', trigger: ['change','blur' ]}
          ],
        },
        dialogVisibleLoading: false,
        showCorporatePay:false,
        form:{
          orderId:'',
          photoList:[],
          corporate:{
            voucherUrl:'',
            remark:'',
          }
        },
        corporatePayRules: {
          photoList: [{ required: true, message: "请上传凭证", trigger: ["change","blur"] }],
      },
      uploadObj: {
        url: process.env.VUE_APP_UPLOAD_FILE_API + "/upload/single/minio",
        Headers: { Authorization: "Bearer " + getToken() },
      },
      corporatePayLoading:false,

      handleExportLoading: false,
      pagePerformTimeList: [], // 场次列表
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      pageList(this.queryParams)
      .then(response => {
          this.dataList = response.data.rows;
          this.total = response.data.total;
          this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if(this.queryParams.time){
        this.queryParams.beginTime = this.queryParams.time[0];
        this.queryParams.endTime = this.queryParams.time[1];
      }else{
        this.queryParams.beginTime = null
        this.queryParams.endTime = null
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.$set(this.queryParams, 'id', '');
      this.$set(this.queryParams, 'status', '');
      this.$set(this.queryParams, 'teamTypeId', '');
      this.$set(this.queryParams, 'teamName', '');
      this.$set(this.queryParams, 'performName', '');
      this.$set(this.queryParams, 'beginTime', '');
      this.$set(this.queryParams, 'endTime', '');
      this.$set(this.queryParams, 'time', '');
      this.$set(this.queryParams, 'performDate', '');
      this.$set(this.queryParams, 'performTimeId', '');
      this.queryParams.pageNum = 1;
      this.handleQuery();
    },
    /** 详情按钮操作 */
    openDetails(row, type) {
      this.$refs["detailsDia"].openDialog("详情", row, type);
    },
    handleOpen(list=[]){
          if(!list||list.length==0) return
          let idList = []
          list.forEach((item,index)=>{
            idList.push(item.id)
          }) 
          this.viewerList = idList
          this.getPrintListApi()
          this.$set(this.ruleForm, 'region', '');
          this.$nextTick(()=>{
            this.$refs.ruleForm.clearValidate('region')
          })
          this.dialogVisible = true
        },
        handleClose(){
          this.dialogVisible = false
        },
        /** 查询打印机列表 */
        getPrintListApi() {
          getPrintListApi({deviceType:5,pageNum: 1,
          pageSize: 999,})
          .then(response => {
              this.printList = response.data.rows;
            }
          );
        },
        /**  选择打印机  */
        selectPrint(){

        },
        // 打印 
        async print(list = []){
          this.$refs.ruleForm.validate(async (valid) => {
            if (valid) {
              this.dialogVisibleLoading = true
              try {
                let res = await printApi({
                  //viewerList:list,
                  orderId: list[0],
                  source: 2,
                  deviceId: this.ruleForm.region
                })
                if(res.code == 200) {
                  let url = res.data.linkIp
                  let printInfo = res.data.printInfo
                  this.connectPrint(url,printInfo)
                }else {
                  throw new Error(res)
                }
              } catch (error) {
                this.dialogVisible = false
                this.dialogVisibleLoading = false
                console.error("error=====",error)
              }
            } else {
              console.log('error submit!!');
              return false;
            }
          });
          
        },
        /**  连接打印机  */
        connectPrint(url,data){
          // let xhr = new XMLHttpRequest();
          // xhr.onreadystatechange = ()=>{
          // if(xhr.readyState == 4){ // 监听请求完成
          //     if((xhr.status >=200 && xhr.status <300) || xhr.status == 304){
          //       console.log(xhr.responseText)
          //       this.dialogVisible = false
          //       this.dialogVisibleLoading = false
          //     }else{
          //       console.log('请求失败')
          //       this.dialogVisible = false
          //       this.dialogVisibleLoading = false
          //     }
          //   }
          // }
          // xhr.open("post", url, true); // 异步请求
          // xhr.send(JSON.stringify(data));

          const ignoreSSL = axios.create({
            httpsAgent: new https.Agent({  
              rejectUnauthorized: false
            }),
            withCredentials: true, // 跨域请求时发送Cookie
            timeout: 60000, // 请求超时
            headers: {
              "Content-Type": "application/json; charset=UTF-8;"
            }
          });
          ignoreSSL.post(url, 
            { ...data }
            ).then(()=>{
            this.dialogVisible = false
            this.dialogVisibleLoading = false
          }).catch(()=>{
            this.dialogVisible = false
            this.dialogVisibleLoading = false
          })
        },
        handleCorporatePay(row){
          console.log('corporatePay',row);
          this.form.orderId = row.id;
          this.showCorporatePay = true;

        },
        handleCorporatePayClose(){
          console.log('1111');
          this.corporatePayLoading = false;
          this.showCorporatePay = false;
        },
        corporatePay(){
          console.log('form',this.form);
          if(this.form.photoList.length<1){
            this.$message.error('请上传凭证');
            return
          }
          this.corporatePayLoading = true;
          const voucherUrl = this.form.photoList.map(item => item.url).join(",");
          this.form.corporate.voucherUrl = voucherUrl;
          gotoCorporatePay(this.form).then((res)=>{
            this.$message.success(res.msg);
            this.corporatePayLoading = false;
            this.handleCorporatePayClose();
          }).catch((err)=>{
            this.corporatePayLoading = false;
            this.$message.error(err.msg);
            console.log('corporatePay err',err);
          })
        },
      /**
     * 剧目海报上传成功
     * @date 2023-11-22
     * @param {any} res
     * @returns {any}
     */
    handlePhotoListSuccess(res) {
      if (res.code === 200) {
        let photo = {
          imageUrl: res?.data?.url,
          url: res?.data?.url,
          photoType: '2'
        }
        if(!this.form.photoList){
          this.form.photoList = []
        }
        // this.form.photoList.push(photo);
        this.$set(this.form.photoList, this.form.photoList.length, photo);
      }
    },
    handleRemove(file, fileList) {
      this.form.photoList.forEach((item, index) => {
        if(item.uid == file.uid){
          this.form.photoList.splice(index, 1)
        }
      })
    },
    /**
     * 上传文件之前之前
     * @date 2023-11-22
     * @param {any} file
     * @returns {any}
     */
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || "image/png";
      if (!isJPG) {
        this.$message.error("上传头像图片只能是jpg或png格式!");
      }
      return isJPG;
    },
    /**
     * 导出报表
     * @date 2022-10-24
     * @returns {any}
     */
     handleExport() {
      this.$confirm('您确定要导出当前查询的数据吗？', '提示', {
        confirmButtonText: '确定 ',
        cancelButtonText: '取消 ',
        type: 'warning'
      })
        .then(() => {
          this.handleExportLoading = true;
          // const { pageNum, pageSize} = this.params;
          let postMap = {}
          for (let key in this.queryParams) {
            if(key != 'pageNum' && key != 'pageSize'){
              postMap[key] = this.queryParams[key]
            }
          }
          downOrderListXls(postMap)
            .then((res) => {
              exportExcel(res, '团购订单', '.xlsx');
              this.handleExportLoading = false;
            })
            .catch((error) => {
              console.log("error===",error)
              this.handleExportLoading = false;
            });
        })
        .catch(() => {
          this.$message.info('您已取消导出！');
        });
    },
    async pagePerformTimeListFun(value) {
      try {
        this.pagePerformTimeList = []
        this.$set(this.queryParams,'performTimeId',null)
        if(!value){
          return
        }
        let { data,code } = await pagePerformTimeList({
          performDate: value,
          pageNum: 1,
          pageSize: 999
        })
        this.pagePerformTimeList = [].concat(data.rows)
      } catch (error) {
        
      }
    },
  }
};
</script>
<style lang="scss">

  .upload-btn {
    width: 100px;
    height: 100px;
    background-color: #fbfdff;
    border: dashed 1px #c0ccda;
    border-radius: 5px;
    i {
      font-size: 30px;
      margin-top: 20px;
    }
    &-text {
      margin-top: -10px;
    }
  }
  .avatar {
    cursor: pointer;
  }

</style>
