<template>
  <div class="app-container">
    <!-- 搜索表单（不变） -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
      <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="patientPhone">
        <el-input v-model="queryParams.patientPhone" 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="orderCode">
        <el-input v-model="queryParams.orderCode" placeholder="请输入订单号" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- 创建时间范围查询 -->
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          size="small"
          style="width: 240px"
        ></el-date-picker>
      </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="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="collectionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="患者姓名" align="center" prop="patientName" />
      <el-table-column label="患者电话" align="center" prop="patientPhone" />
      <el-table-column label="手写信息采集表" align="center" prop="billImgUrl" width="120">
        <template slot-scope="scope">
          <el-image
            style="width: 50px; height: 50px"
            :src="scope.row.billImgUrl"
            :preview-src-list="[scope.row.billImgUrl]"
            fit="cover">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <!-- 新增补充图片列 -->
      <el-table-column label="补充图片" align="center" prop="extraImgUrl" width="120">
        <template slot-scope="scope">
          <div v-if="scope.row.extraImgUrl">
            <el-image
              style="width: 50px; height: 50px"
              :src="getExtraImgList(scope.row.extraImgUrl)[0]"
              :preview-src-list="getExtraImgList(scope.row.extraImgUrl)"
              fit="cover">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
            <span v-if="getExtraImgList(scope.row.extraImgUrl).length > 1" style="margin-left: 4px; font-size: 12px; color: #999;">
              +{{ getExtraImgList(scope.row.extraImgUrl).length - 1 }}
            </span>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="订单号" align="center" prop="orderCode" />
      <el-table-column label="创建销售" align="center" prop="companyUserName" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(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" />

  </div>
</template>

<script>
import { listCollection, getCollection,delCollection,} from "@/api/company/handwriteCollection";
import ImageUpload from "@/components/ImageUpload";

export default {
  name: "HandwriteCollection",
  components: { ImageUpload },
  data() {
    return {
      loading: true,
      showSearch: true,
      total: 0,
      collectionList: [],
      title: "",
      open: false,
      ids: [],
      single: true,
      multiple: true,
      originalOrderCode: null,
      orderInfoVisible: false,
      orderInfo: {},
      ocrLoading: false,
      ocrMsg: '',
      statusOptions: [],
      dateRange: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        patientName: null,
        companyUserName: null,
        patientPhone: null,
        orderCode: null
      },
      form: {},
      rules: {
        patientName: [
          { required: true, message: "患者姓名不能为空", trigger: "blur" }
        ],
        patientPhone: [
          { required: true, message: "患者电话不能为空", trigger: "blur" },
          { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" }
        ],
        orderCode: [
          { required: true, message: "订单号不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("store_order_status").then(response => {
      this.statusOptions = response.data;
    }).catch(() => {
      this.statusOptions = [];
    });
  },
  methods: {
    getList() {
      this.loading = true;
      // 处理日期范围参数
      const params = { ...this.queryParams };
      if (this.dateRange && this.dateRange.length === 2) {
        params.startDate = this.dateRange[0];
        params.endDate = this.dateRange[1];
      }
      listCollection(this.queryParams).then(response => {
        this.collectionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.dateRange = []; // 重置日期范围
      this.$refs.queryForm.resetFields();
      this.handleQuery();
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加手写信息采集表";
      this.orderInfoVisible = false;
      this.ocrMsg = '';
      // 新增模式，允许自动识别
      this.isNewRecord = true;
    },
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids[0];
      getCollection(id).then(response => {
        this.form = response.data;
        this.originalOrderCode = this.form.orderCode;
        this.open = true;
        this.title = "修改手写信息采集表";
        this.orderInfoVisible = false;
        this.ocrMsg = '';
        // 修改模式，不自动识别已有图片
        this.isNewRecord = false;
      });
    },
    handleDelete(row) {
      const ids = row.id || this.ids.join(",");
      this.$confirm('是否确认删除选中的数据项？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return delCollection(ids);
      }).then(() => {
        this.getList();
        this.$message.success("删除成功");
      }).catch(() => {});
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    // 将逗号分隔的字符串转为图片URL数组
    getExtraImgList(str) {
      if (!str) return [];
      return str.split(',').filter(url => url.trim() !== '');
    },
    reset() {
      this.form = {
        id: null,
        patientName: null,
        companyUserName: null,
        patientPhone: null,
        billImgUrl: null,
        orderCode: null,
        extraImgUrl: ''
      };
      this.originalOrderCode = null;
      this.ocrMsg = '';
      this.ocrLoading = false;
      if (this.$refs.form) {
        this.$refs.form.resetFields();
      }
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    parseTime(time) {
      if (!time) return '';
      const date = new Date(time);
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hour = date.getHours().toString().padStart(2, '0');
      const minute = date.getMinutes().toString().padStart(2, '0');
      const second = date.getSeconds().toString().padStart(2, '0');
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    }
  }
};
</script>

<style scoped>
.order-info-card {
  border-radius: 4px;
  overflow: hidden;
}
.success-msg {
  color: #67C23A;
}
.error-msg {
  color: #F56C6C;
}
</style>
