<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="85px">
      <el-form-item label="公司名" prop="companyId">
        <el-select filterable  v-model="queryParams.companyId" placeholder="请选择公司名"  @change="companyChange" clearable size="small">
          <el-option
            v-for="item in companys"
            :key="item.companyId"
            :label="item.companyName"
            :value="item.companyId"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <treeselect style="width: 220px" :clearable="false"  v-model="queryParams.deptId"  :options="deptOptions" clearable :show-count="true" placeholder="请选择归属部门"  />
      </el-form-item>
      <el-form-item label="订单号" prop="orderSn">
        <el-input
          v-model="queryParams.orderSn"
          placeholder="请输入订单号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户电话" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入用户电话"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="加密号码" prop="phoneMk">
        <el-input
          v-model="queryParams.phoneMk"
          placeholder="请输入用户电话"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="医生名称" prop="doctorName">
        <el-input
          v-model="queryParams.doctorName"
          placeholder="请输入医生名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="员工" prop="companyUserName">
        <el-input
          v-model="queryParams.companyUserName"
          placeholder="员工"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="收货人" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入收货人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="收货人电话" prop="userPhone">
        <el-input
          v-model="queryParams.userPhone"
          placeholder="请输入收货人电话"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="套餐名称" prop="packageName">
        <el-input
          v-model="queryParams.packageName"
          placeholder="请输入套餐名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="是否支付" prop="isPay">
        <el-select v-model="queryParams.isPay" placeholder="请选择是否支付" clearable size="small">
          <el-option
            v-for="dict in isPayOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="来源" prop="source">
        <el-select v-model="queryParams.source" placeholder="请选择是否支付" clearable size="small">
          <el-option
            v-for="dict in sourceOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="所属小程序" prop="coursePlaySourceConfigId">
        <el-select v-model="queryParams.coursePlaySourceConfigId" placeholder="请选择所属小程序" clearable size="small">
          <el-option
            v-for="dict in appMallOptions"
            :key="dict.id"
            :label="dict.name + '(' + dict.appid + ')'"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker v-model="startTime" size="small" style="width: 220px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" @change="startChange"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker v-model="endTime" size="small" style="width: 220px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" @change="endChange"></el-date-picker>
        </el-form-item>
        <el-form-item label="下单时间" prop="createTime">
          <el-date-picker v-model="createTime" size="small" style="width: 220px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" @change="xdChange"></el-date-picker>
        </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-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['his:packageOrder:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-tabs type="card" v-model="actName" @tab-click="handleClickX">
      <el-tab-pane label="全部订单" name="10"></el-tab-pane>
      <el-tab-pane v-for="(item,index) in statusOptions" :label="item.dictLabel" :name="item.dictValue"></el-tab-pane>
    </el-tabs>
    <el-table height="500" v-loading="loading" border :data="packageOrderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单号" align="center" prop="orderSn" width="120px"/>
      <el-table-column label="所属公司" align="center" prop="companyName" />
      <el-table-column label="员工" align="center" prop="companyUserName" />
      <el-table-column label="小程序名称" align="center" prop="miniProgramName" width="120px" />
      <el-table-column label="套餐名称" align="center" prop="packageName" />
      <el-table-column label="套餐别名" align="center" prop="packageSecondName" width="100px"/>
      <el-table-column label="天数" align="center" prop="days" />
      <el-table-column label="就诊人" align="center" prop="patientName" />
      <el-table-column label="应收金额" align="center" prop="payPrice" />
      <el-table-column label="实收金额" align="center" prop="payMoney" />
      <el-table-column label="支付类别" align="center" prop="payType">
        <template slot-scope="scope">
          <dict-tag :options="payTypeOptions" :value="scope.row.payType"/>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="status" >
        <template slot-scope="scope">
          <dict-tag :options="statusOptions" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="套餐类型" align="center" prop="packageSubType" >
        <template slot-scope="scope">
          <dict-tag :options="packageSubTypeOptions" :value="scope.row.packageSubType"/>
        </template>
      </el-table-column>
      <el-table-column label="订单来源" align="center" prop="source" >
        <template slot-scope="scope">
          <dict-tag :options="sourceOptions" :value="scope.row.source"/>
        </template>
      </el-table-column>
      <el-table-column label="下单时间" align="center" prop="createTime" width="180" />
      <el-table-column label="支付时间" align="center" prop="payTime" width="180" />
      <el-table-column label="开始时间" align="center" prop="startTime" width="180" />
      <el-table-column label="结束时间" align="center" prop="finishTime" width="180" />
      <el-table-column label="物流状态" align="center" prop="deliveryStatus" >
        <template slot-scope="scope">
          <dict-tag :options="deliveryStatusOptions" :value="scope.row.deliveryStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="结算状态" align="center" prop="deliveryPayStatus" >
        <template slot-scope="scope">
          <dict-tag :options="deliveryPayStatusOptions" :value="scope.row.deliveryPayStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="150px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handledetails(scope.row)"
          >详情
          </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"
    />
    <!-- 添加或修改套餐订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单号" prop="orderSn">
          <el-input v-model="form.orderSn" placeholder="请输入订单号" />
        </el-form-item>
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="医生ID" prop="doctorId">
          <el-input v-model="form.doctorId" placeholder="请输入医生ID" />
        </el-form-item>
        <el-form-item label="套餐ID" prop="packageId">
          <el-input v-model="form.packageId" placeholder="请输入套餐ID" />
        </el-form-item>
        <el-form-item label="套餐名称" prop="packageName">
          <el-input v-model="form.packageName" placeholder="请输入套餐名称" />
        </el-form-item>
        <el-form-item label="支付金额" prop="payMoney">
          <el-input v-model="form.payMoney" placeholder="请输入支付金额" />
        </el-form-item>
        <el-form-item label="是否支付" prop="isPay">
          <el-select v-model="form.isPay" placeholder="请选择是否支付">
            <el-option
              v-for="dict in isPayOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="天数" prop="days">
          <el-input v-model="form.days" placeholder="请输入天数" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="parseInt(dict.dictValue)"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable size="small"
                          v-model="form.startTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="finishTime">
          <el-date-picker clearable size="small"
                          v-model="form.finishTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择结束时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-drawer
      :with-header="false"
      size="75%"
      :title="show.title" :visible.sync="show.open">
      <packageOrderDetails  ref="Details" />
    </el-drawer>
  </div>
</template>

<script>
import { listPackageOrder, getPackageOrder, delPackageOrder, addPackageOrder, updatePackageOrder, exportPackageOrder } from "@/api/his/packageOrder";
import { getCompanyList } from "@/api/company/company";
import packageOrderDetails from '../../components/his/packageOrderDetails.vue';
import { treeselect } from "@/api/company/companyDept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getTask } from "@/api/common";
import {list as getAppMallOptions} from '@/api/course/coursePlaySourceConfig';
export default {
  watch: {
    // 监听deptId
    'deptId': 'currDeptChange'
  },
  name: "PackageOrder",
  components: {packageOrderDetails ,Treeselect },
  data() {
    return {
      companys:[],
      deptOptions:[],
      companyId:undefined,
      deptId:undefined,
      show:{
        open:false,
      },
      sourceOptions:[],
      actName:"2",
      // 遮罩层
      loading: true,
      startTime:null,
      // 导出遮罩层
      exportLoading: false,
      // 导出任务检查计数器
      exportCheckCount: 0,
      // 选中数组
      ids: [],
      createTime:null,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      endTime:null,
      // 总条数
      total: 0,
      // 套餐订单表格数据
      packageOrderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否支付字典
      isPayOptions: [],
      // 状态字典
      statusOptions: [],
      refundStatusOptions: [],
      packageSubTypeOptions: [],
      payTypeOptions:[],
      deliveryPayStatusOptions:[],
      deliveryStatusOptions:[],
      appMallOptions:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderSn: null,
        userId: null,
        doctorId: null,
        doctorName: null,
        phone: null,
        phoneMk: null,
        packageId: null,
        packageName: null,
        payMoney: null,
        isPay: null,
        days: null,
        status: 2,
        startTime: null,
        finishTime: null,
        sTime:null,
        eTime:null,
        stTime:null,
        endTime:null,
        endStartTime:null,
        endEndTime:null,
        companyUserName:null,
        companyName:null,
        deptId:null,
        source:null,
        coursePlaySourceConfigId:null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    getCompanyList().then(response => {
      this.companys = response.data;
      if(this.companys!=null&&this.companys.length>0){
        this.companyId=this.companys[0].companyId;
        this.getTreeselect();
      }
      this.companys.push({companyId:"-1",companyName:"无"})
    });
    this.getList();
    this.getDicts("sys_company_or").then(response => {
      this.isPayOptions = response.data;
    });
    this.getDicts("sys_package_order_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("sys_refund_status").then(response => {
      this.refundStatusOptions = response.data;
    });
    this.getDicts("sys_order_source").then(response => {
      this.sourceOptions = response.data;
    });
    this.getDicts("sys_package_pay_type").then(response => {
      this.payTypeOptions = response.data;
    });
    this.getDicts("sys_store_delivery_pay_status").then(response => {
      this.deliveryPayStatusOptions = response.data;
    });
    this.getDicts("sys_store_order_delivery_status").then(response => {
      this.deliveryStatusOptions = response.data;
    });
    this.getDicts("sys_package_sub_type").then(response => {
      this.packageSubTypeOptions = response.data;
    });
    
    // 获取小程序选项列表
    this.getAppMallOptions();
  },
  methods: {
    /** 查询套餐订单列表 */
    getList() {
      this.loading = true;
      listPackageOrder(this.queryParams).then(response => {
        this.packageOrderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handledetails(row){
      this.show.open=true;
      setTimeout(() => {
        this.$refs.Details.getDetails(row.orderId);
      }, 1);
    },
    startChange(){
      if(this.startTime!=null){
        this.queryParams.sTime=this.startTime[0];
        this.queryParams.eTime=this.startTime[1];
      }else{
        this.queryParams.sTime=null;
        this.queryParams.eTime=null;
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        orderId: null,
        orderSn: null,
        userId: null,
        doctorId: null,
        packageId: null,
        packageName: null,
        payMoney: null,
        isPay: null,
        days: null,
        status: 0,
        startTime: null,
        finishTime: null,
        createTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.startTime=null;
      this.queryParams.sTime=null;
      this.queryParams.eTime=null;
      this.createTime=null;
      this.queryParams.stTime=null;
      this.queryParams.endTime=null;
      this.endTime=null;
      this.queryParams.endStartTime=null;
      this.queryParams.endEndTime=null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    xdChange(){
      if(this.createTime!=null){
        this.queryParams.stTime=this.createTime[0];
        this.queryParams.endTime=this.createTime[1];
      }else{
        this.queryParams.stTime=null;
        this.queryParams.endTime=null;
      }
    },
    endChange(){
      if(this.endTime!=null){
        this.queryParams.endStartTime=this.endTime[0];
        this.queryParams.endEndTime=this.endTime[1];
      }else{
        this.queryParams.endStartTime=null;
        this.queryParams.endEndTime=null;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加套餐订单";
    },
    handleClickX(tab, event) {
      if(tab.name=="10"){
        this.queryParams.status=null;
      }else{
        this.queryParams.status=tab.name;
      }
      this.handleQuery();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const orderId = row.orderId || this.ids
      getPackageOrder(orderId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改套餐订单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.orderId != null) {
            updatePackageOrder(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPackageOrder(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orderIds = row.orderId || this.ids;
      this.$confirm('是否确认删除套餐订单编号为"' + orderIds + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delPackageOrder(orderIds);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
	  var that=this;
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有套餐订单数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportPackageOrder(queryParams);
      }).then(response => {
        if(response.code==200){
          that.msgSuccess(response.msg);
          that.taskId=response.data;
          that.exportCheckCount = 0; // 添加检查计数器
          that.time=setInterval(function(){
            that.exportCheckCount++;
            //查任务状态
            getTask(that.taskId).then(res => {
              // 任务完成
              if(res.data.status==1){
                that.exportLoading = false;
                clearInterval(that.time);
                that.time=null;
                that.download(res.data.fileUrl);
              }
              // 任务失败
              else if(res.data.status==-1 || res.data.status==2){
                that.exportLoading = false;
                clearInterval(that.time);
                that.time=null;
                that.msgError('导出任务失败，请重试');
              }
              // 超时处理（检查超过30次，即5分钟）
              else if(that.exportCheckCount > 30){
                that.exportLoading = false;
                clearInterval(that.time);
                that.time=null;
                that.msgError('导出任务超时，请稍后重试');
              }
            }).catch(err => {
              // API调用失败
              that.exportCheckCount++;
              if(that.exportCheckCount > 30){
                that.exportLoading = false;
                clearInterval(that.time);
                that.time=null;
                that.msgError('导出任务查询失败，请重试');
              }
            });
          },10000); // 10秒查询一次
        }
        else{
          that.msgError(response.msg);
          that.exportLoading = false;
        }
      }).catch(() => {
        that.exportLoading = false;
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      var that=this;
      var param={companyId:this.companyId}
      treeselect(param).then((response) => {
        this.deptOptions = response.data;
        console.log(this.deptOptions)
        if(response.data!=null&&response.data.length>0){
          //this.queryParams.deptId=response.data[0].id;
        }
      });
    },
    companyChange(val){
      this.companyId=val;
      this.getTreeselect();
    },
    currDeptChange(val){
      this.queryParams.deptId=val;
      this.getList();
    },
    // 获取小程序选项列表
    getAppMallOptions() {
      getAppMallOptions({pageNum:1,pageSize:100,isMall:1}).then(response => {
        this.appMallOptions = response.rows;
      })
    },
  }
};
</script>
