<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
<!--      <el-form-item label="公司名称" prop="companyId" >-->
<!--        <el-select v-model="queryParams.companyId" placeholder="请选择所属公司" filterable size="small">-->
<!--          <el-option v-for="(option, index) in companyList" :key="index" :value="option.dictValue" :label="option.dictLabel"></el-option>-->
<!--        </el-select>-->
<!--      </el-form-item>-->

      <el-form-item label="处方类型" prop="prescribeType">
       <el-select v-model="queryParams.prescribeType" placeholder="处方类型" clearable size="small">
               <el-option
                 v-for="dict in prescribeType"
                 :key="dict.dictValue"
                 :label="dict.dictLabel"
                 :value="dict.dictValue"
               />
       </el-select>

      </el-form-item>


      <el-form-item label="患者名称" prop="patientName">
        <el-input
          v-model="queryParams.patientName"
          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="orderCode">
        <el-input
          v-model="queryParams.orderCode"
          placeholder="请输入药品订单单号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="处方单编号" prop="prescribeCode">
        <el-input
          v-model="queryParams.prescribeCode"
          placeholder="请输入处方单编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="患者电话" prop="patientTel">
        <el-input
          v-model="queryParams.patientTel"
          placeholder="请输入患者电话"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="药品订单状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="药品订单状态" clearable size="small">
                <el-option
                  v-for="dict in orderStatusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
      </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="change"></el-date-picker>
        </el-form-item>


        <el-form-item label="审核时间" prop="auditTime">
            <el-date-picker v-model="auditTime" size="small" style="width: 220px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" @change="change"></el-date-picker>
        </el-form-item>

      <!-- 开方耗时区间筛选 -->
      <el-form-item label="开方耗时" prop="operateTimeRange">
        <el-input-number
          v-model="operateTime.minVal"
          :min="0"
          :controls="false"
          size="small"
          placeholder="最小值"
          style="width: 100px"
        />
        <el-select v-model="operateTime.minUnit" size="small" style="width: 70px; margin: 0 8px">
          <el-option label="秒" value="sec" />
          <el-option label="分" value="min" />
        </el-select>
        ~
        <el-input-number
          v-model="operateTime.maxVal"
          :min="0"
          :controls="false"
          size="small"
          placeholder="最大值"
          style="width: 100px; margin-left: 8px"
        />
        <el-select v-model="operateTime.maxUnit" size="small" style="width: 70px; margin: 0 8px">
          <el-option label="秒" value="sec" />
          <el-option label="分" value="min" />
        </el-select>
      </el-form-item>

      <el-form-item label="医生组别" prop="groupCode">
        <el-select v-model="queryParams.groupCode" placeholder="请选择医生组别" clearable size="small">
          <el-option
            v-for="dict in groupCodeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </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-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['his:prescribe:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="small"
          :loading="exportLoading"
          @click="handleExportMessageFeedback"
          v-hasPermi="['his:prescribe:messageFeedbackExport']"
        >医疗信息反馈单</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 prescribeStatusOptions" :label="item.dictLabel" :name="item.dictValue"></el-tab-pane>
    </el-tabs>
    <el-table heiget="600" v-loading="loading" border :data="prescribeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column label="处方单编号" align="center" prop="prescribeCode" width="180px" />
      <el-table-column label="药品订单编号" align="center" prop="orderCode" width="180px" />
      <el-table-column label="处方类型" align="center" prop="prescribeType" >
            <template slot-scope="scope">
              <dict-tag :options="prescribeType" :value="scope.row.prescribeType"/>
            </template>
      </el-table-column>
      <el-table-column label="医生组别" align="center" prop="groupCode">
        <template slot-scope="scope">
          <dict-tag :options="groupCodeOptions" :value="scope.row.groupCode"/>
        </template>
      </el-table-column>
      <el-table-column label="患者年龄" align="center" prop="patientAge" />
      <el-table-column label="患者姓名" align="center" prop="patientName" />
      <el-table-column label="诊断" align="center" prop="diagnose" />
      <el-table-column label="医生名称" align="center" prop="doctorName" />
      <el-table-column label="药师名称" align="center" prop="doctorDrugName">
        <template slot-scope="scope">
          <!-- 使用 v-if 指令，根据当前行的 status 值决定是否渲染药师名称 -->
          <span v-if="scope.row.status !== 0">{{ scope.row.doctorDrugName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" >
        <template slot-scope="scope">
          <dict-tag :options="prescribeStatusOptions" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="药品订单状态" align="center" prop="orderStatus" >
            <template slot-scope="scope">
              <dict-tag :options="orderStatusOptions" :value="scope.row.orderStatus"/>
            </template>
      </el-table-column>
      <el-table-column label="审核时间" align="center" prop="auditTime" width="180" />
      <el-table-column
        prop="operate_second"
        label="操作时长"
        min-width="140"
      >
        <template slot-scope="{ row }">
          {{ formatSeconds(row.operateSecond) }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="100px">
        <template slot-scope="scope">
           <el-button
                      size="mini"
                      type="text"
                      @click="handledetails(scope.row)"
                    >查看
          </el-button>

          <el-button size="mini" type="text"
                     @click="handleRecord(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-drawer
        :with-header="false"
        size="75%"
         :title="show.title" :visible.sync="show.open">
     <prescribeDetails  ref="Details" />
   </el-drawer>



    <el-dialog title="审核记录" :visible.sync="recordDialogVisible" width="1000px" append-to-body>
      <el-table v-loading="recordLoading" :data="recordList" border style="width: 100%; margin-top: 10px;"
                max-height="400">
        <el-table-column label="审核药师" align="center" prop="drugDoctorName"  />
        <el-table-column label="拒方原因" align="center" prop="auditReason" show-overflow-tooltip />
        <el-table-column label="处方图片" align="center" width="140">
          <template slot-scope="scope">
            <el-image v-if="scope.row.prescribeImgUrl" :src="scope.row.prescribeImgUrl"
                      :preview-src-list="[scope.row.prescribeImgUrl]" style="width: 120px; height: 120px" fit="cover" />
            <span v-else>无</span>
          </template>
        </el-table-column>
        <el-table-column label="审核时间" align="center" prop="createTime"  />
        <el-table-column label="审核状态" align="center" width="120">
          <template slot-scope="scope">
            {{ statusFormat(scope.row.auditStatus != null ? scope.row.auditStatus : scope.row.status) }}
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { listPrescribe, getPrescribe, delPrescribe, addPrescribe, updatePrescribe, exportPrescribe,exportMessageFeedback,recordList } from "@/api/his/prescribe";
import prescribeDetails from '../../components/his/prescribeDetails.vue';
import {allList}from "@/api/company/company";
import { getTask } from "@/api/common";
import {list as getAppMallOptions} from '@/api/course/coursePlaySourceConfig';
export default {
  name: "Prescribe",
  components: { prescribeDetails },
  data() {
    return {
      // 医生组别字典
      groupCodeOptions: [],
      //审核记录数据
      recordLoading: false,
      recordList: [],
      recordDialogVisible: false,//审核记录弹窗控制
      operateTime: {
        minVal: null,
        minUnit: 'sec', // 默认单位：秒
        maxVal: null,
        maxUnit: 'sec'
      },
      dateRange: null,
      companyList:[],
      createTime:null,
      pjtUrl: process.env.VUE_APP_BASE_API+"/",
      show:{
              title:"订单详情",
              open:false,
            },
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      auditTime:null,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 处方表格数据
      prescribeList: [],
      orderStatusOptions:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        groupCode: null,
        pageNum: 1,
        pageSize: 10,
        prescribeType: null,
        inquiryOrderId: null,
        storeOrderId: null,
        userId: null,
        patientId: null,
        prescribeCode: null,
        patientDescs: null,
        nowIllness: null,
        historyIllness: null,
        patientAge: null,
        patientName: null,
        weight: null,
        sTime:null,
        eTime:null,
        isHistoryAllergic: null,
        historyAllergic: null,
        liverUnusual: null,
        renalUnusual: null,
        isLactation: null,
        patientTel: null,
        patientGender: null,
        recordPic: null,
        prescribeImgUrl: null,
        auditReason: null,
        diagnose: null,
        doctorId: null,
        status: null,
        auditTime: null,
        auditSTime:null,
        auditETime:null,
        doctorName:null,
        orderStatus:null,
        appId:null,
        minOperateSeconds: null,
        maxOperateSeconds: null,
      },
       actName:"10",
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      prescribeStatusOptions:[],
      prescribeType:[],
      orOptions:[],
      sexOptions:[],
      appMallOptions:[],
    };
  },
  created() {
    this.getDicts("doctor_group").then(response => {
      this.groupCodeOptions = response.data;
    });
    this.getAllCompany();
    this.getDicts("sys_prescribe_status").then(response => {
        this.prescribeStatusOptions = response.data;
      });
    this.getDicts("sys_prescribe_type").then(response => {
        this.prescribeType = response.data;
      });
    this.getDicts("sys_sex").then(response => {
        this.sexOptions = response.data;
      });
    this.getDicts("sys_company_or").then(response => {
        this.orOptions = response.data;
      });
    this.getDicts("sys_order_status").then(response => {
        this.orderStatusOptions = response.data;
      });

    this.getAppMallOptions();
    this.getList();
  },
  methods: {
    statusFormat(val) {
      if (val === 0 || val === '0') return '待审核'
      if (val === 1 || val === '1') return '审核通过'
      if (val === 2 || val === '2') return '审核不通过'
      return '-'
    },
    getAppMallOptions() {
      getAppMallOptions({pageNum:1,pageSize:100,isMall:1}).then(response => {
        this.appMallOptions = response.rows;
      })
    },
    getAllCompany() {
      allList().then(response => {
        this.companyList = response.rows;
      });
    },
    handleClickX(tab, event) {
     if(tab.name=="10"){
       this.queryParams.status=null;
     }else{
       this.queryParams.status=tab.name;
     }
      this.handleQuery();
    },
    handledetails(row){
         this.show.open=true;
         setTimeout(() => {
              this.$refs.Details.getDetails(row.prescribeId);
         }, 1);
     },
    //审核记录
    handleRecord(row) {
      this.recordDialogVisible = true;
      this.recordLoading = true;
      recordList(row.prescribeId).then(res =>{
        this.recordLoading = false;
        this.recordList = res.data;
      })
    },
    /** 查询处方列表 */
    getList() {
      this.loading = true;

      // 构造请求参数（避免直接修改 queryParams）
      const params = { ...this.queryParams };

      // 处理开方时间
      if (this.dateRange?.length === 2) {
        params.startOperateTime = this.dateRange[0];
        params.endOperateTime = this.dateRange[1];
      } else {
        delete params.startOperateTime;
        delete params.endOperateTime;
      }

      listPrescribe(params).then(response => {
        this.prescribeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    change(){
      if(this.createTime!=null){
        this.queryParams.sTime=this.createTime[0];
        this.queryParams.eTime=this.createTime[1];
      }else{
        this.queryParams.sTime=null;
        this.queryParams.eTime=null;
      }
      if(this.auditTime!=null){
        this.queryParams.auditSTime=this.auditTime[0];
        this.queryParams.auditETime=this.auditTime[1];
      }else{
        this.queryParams.auditSTime=null;
        this.queryParams.auditETime=null;
      }


    },
    // 表单重置
    reset() {
      this.form = {
        prescribeId: null,
        prescribeType: null,
        inquiryOrderId: null,
        storeOrderId: null,
        userId: null,
        patientId: null,
        prescribeCode: null,
        patientDescs: null,
        nowIllness: null,
        historyIllness: null,
        patientAge: null,
        patientName: null,
        weight: null,
        isHistoryAllergic: null,
        historyAllergic: null,
        liverUnusual: null,
        renalUnusual: null,
        isLactation: null,
        patientTel: null,
        patientGender: null,
        recordPic: null,
        prescribeImgUrl: null,
        auditReason: null,
        diagnose: null,
        doctorId: null,
        createTime: null,
        status: 0,
        auditTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      const toSeconds = (val, unit) => {
        if (val == null || val === '') return null;
        return unit === 'min' ? val * 60 : val;
      };
      const minSec = toSeconds(this.operateTime.minVal, this.operateTime.minUnit);
      const maxSec = toSeconds(this.operateTime.maxVal, this.operateTime.maxUnit);

      //核心校验：如果两个值都存在，max 不能小于 min
      if (minSec != null && maxSec != null && minSec > maxSec) {
        this.$message.warning('开方耗时：最大值不能小于最小值！');
        return; // 阻止查询
      }
      if (minSec === 0 && maxSec === 0) {
        delete this.queryParams.minOperateSeconds;
        delete this.queryParams.maxOperateSeconds;
      } else {
        // 否则正常赋值（可能是 null，也可能是有效数字）
        this.queryParams.minOperateSeconds = minSec;
        this.queryParams.maxOperateSeconds = maxSec;
      }

      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.createTime=null;
      this.queryParams.sTime=null;
      this.queryParams.eTime=null;
      this.auditTime=null;
      this.dateRange = null;
      this.queryParams.auditSTime=null;
      this.queryParams.auditETime=null;
      this.operateTime = {
        minVal: null,
        minUnit: 'sec',
        maxVal: null,
        maxUnit: 'sec'
      };
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.prescribeId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加处方";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const prescribeId = row.prescribeId || this.ids
      getPrescribe(prescribeId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改处方";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.prescribeId != null) {
            updatePrescribe(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPrescribe(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const prescribeIds = row.prescribeId || this.ids;
      this.$confirm('是否确认删除处方编号为"' + prescribeIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delPrescribe(prescribeIds);
        }).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 exportPrescribe(queryParams);
        }).then(response => {
			if(response.code==200){
			that.msgSuccess(response.msg);
			that.taskId=response.data;
			that.time=setInterval(function(){
			  //查订单
			  getTask(that.taskId).then(res => {
				if(res.data.status==1){
				  that.exportLoading = false;
				  clearTimeout(that.time)
				  that.time=null;
				  that.download(res.data.fileUrl);
				}
			  });
			},10000);
		  }
        }).catch(() => {});
    },
     /** 导出按钮操作 */
     handleExportMessageFeedback() {
		 var that=this;
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有医疗信息反馈单数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportMessageFeedback(queryParams);
        }).then(response => {
			if(response.code==200){
			that.msgSuccess(response.msg);
			that.taskId=response.data;
			that.time=setInterval(function(){
			  //查订单
			  getTask(that.taskId).then(res => {
				if(res.data.status==1){
				  that.exportLoading = false;
				  clearTimeout(that.time)
				  that.time=null;
				  that.download(res.data.fileUrl);
				}
			  });
			},10000);
		  }
        }).catch(() => {});
    },
    // 表格排序变化（点击表头排序）
    handleSortChange({ prop, order }) {
      if (order === 'ascending') {
        this.queryParams.sortField = prop;
        this.queryParams.sortOrder = 'asc';
      } else if (order === 'descending') {
        this.queryParams.sortField = prop;
        this.queryParams.sortOrder = 'desc';
      } else {
        // 取消排序
        delete this.queryParams.sortField;
        delete this.queryParams.sortOrder;
      }
      this.handleQuery(); // 重新查询
    },
    // 秒数转“X分Y秒”
    formatSeconds(seconds) {
      if (seconds == null || seconds === '') return '0秒'
      const sec = Math.floor(Number(seconds))
      const min = Math.floor(sec / 60)
      const remainingSec = sec % 60
      if (min > 0) {
        return `${min}分${remainingSec}秒`
      }
      return `${remainingSec}秒`
    }
  }
};
</script>
