<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <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="doctorName">
        <el-input
          v-model="queryParams.doctorName"
          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="orderCode">
        <el-input
          v-model="queryParams.orderCode"
          placeholder="请输入订单号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="当前状态" prop="currentStep">
        <el-select v-model="queryParams.currentStep" placeholder="当前状态" clearable size="small">
          <el-option
            v-for="dict in currentStepOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="完成时间" prop="completedTime">
        <el-date-picker clearable size="small"
          v-model="queryParams.completedTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择完成时间">
        </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-table border v-loading="loading" :data="collectionScheduleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="客户姓名" align="center" prop="userName" />
      <el-table-column label="约诊医生" align="center" prop="doctorName" />
      <el-table-column label="订单号" align="center" prop="orderCode" />
      <el-table-column label="挂载商品" align="center" prop="packageName" />
      <el-table-column label="当前状态" align="center" prop="currentStep">
        <template slot-scope="scope">
          <el-tag
            v-if="scope.row.currentStep != null"
            :type="stepColorMap[scope.row.currentStep] || 'info'"
            size="small"
          >
            {{ getStepLabel(scope.row.currentStep) }}
          </el-tag>
          <span v-else>—</span>
        </template>
      </el-table-column>
      <el-table-column label="完成时间" align="center" prop="completedTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.completedTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="中止时间" align="center" prop="terminatedTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.terminatedTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <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="endProcess(scope.row)"
            v-hasPermi="['his:collectionSchedule:stop']"
            :disabled="scope.row.status !== 1"
            :style="{ color: scope.row.status === 1 ? '#f56c6c' : '#999' }"
          >终止</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="终止进度" :visible.sync="endProcessVisible" width="400px" @close="resetEndForm">
      <el-form :model="endForm" ref="endFormRef" label-width="80px">
        <el-form-item label="终止原因" prop="remark" :rules="[{ required: true, message: '请输入终止原因', trigger: 'blur' }]">
          <el-input
            v-model="endForm.remark"
            type="textarea"
            :rows="4"
            placeholder="请输入终止原因"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="endProcessVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEndProcess">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listCollectionSchedule, addCollectionSchedule, updateCollectionSchedule, exportCollectionSchedule,getCollectionScheduleSteps,stop } from "@/api/store/collectionSchedule";

export default {
  name: "CollectionSchedule",
  data() {
    // 定义状态颜色映射（若依常用色系）
    const stepColorMap = {
      1: 'primary',   // 待用户第一次确认 —— 蓝色
      2: 'warning',   // 待开方 —— 橙色
      3: 'danger',    // 待药师审核 —— 红色
      4: 'success',   // 待建议 —— 绿色
      5: 'info',      // 待用户二次确认 —— 灰蓝
      6: 'success'    // 完成 —— 蓝色
    };
    return {
      // === 新增：终止弹窗相关 ===
      endProcessVisible: false,
      endForm: {
        id: null,
        collectionId: null,
        remark: ''
      },
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户信息采集进度表格数据
      collectionScheduleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 当前流程节点字典:(1:待用户第一次确认、2：待开方、3：待药师审核、4：待建议、5：待用户二次确认、6：完成)；其中带疗法模式有1，2，3，5,6；无疗法模式只有1，4，5,6
      currentStepOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        collectionId: null,
        userId: null,
        userName: null,
        doctorId: null,
        doctorName: null,
        orderCode: null,
        packageId: null,
        packageName: null,
        currentStep: null,
        status: null,
        completedTime: null,
        terminatedTime: null,
        terminatedBy: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      stepColorMap, // 暴露给模板使用
    };
  },
  created() {
    this.getList();
    getCollectionScheduleSteps().then(response => {
      this.currentStepOptions = response.data;
    });
  },
  methods: {
    /** 查询用户信息采集进度列表 */
    getList() {
      this.loading = true;
      listCollectionSchedule(this.queryParams).then(response => {
        this.collectionScheduleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        collectionId: null,
        userId: null,
        userName: null,
        doctorId: null,
        doctorName: null,
        orderCode: null,
        packageId: null,
        packageName: null,
        currentStep: null,
        status: 0,
        createTime: null,
        completedTime: null,
        terminatedTime: null,
        terminatedBy: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 终止按钮操作 - 打开弹窗 */
    endProcess(row) {
      this.endForm.id = row.id;
      this.endForm.collectionId = row.collectionId;
      this.endForm.remark = '';
      this.endProcessVisible = true;
    },
    /** 提交终止操作 */
    /** 提交终止操作 */
    submitEndProcess() {
      this.$refs["endFormRef"].validate(valid => {
        if (valid) {
          const { id, collectionId, remark } = this.endForm
          this.$confirm('确认终止该采集进度？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            stop({ id, collectionId, remark }).then(response => {
              this.msgSuccess("终止成功");
              this.endProcessVisible = false;
              this.getList();
            }).catch(() => {
              // 可选：错误提示
            });
          }).catch(() => {
            // 取消
          });
        }
      });
    },
    /** 重置终止表单 */
    resetEndForm() {
      this.$refs["endFormRef"] && this.$refs["endFormRef"].resetFields();
      this.endForm.id = null;
      this.endForm.collectionId = null;
      this.endForm.remark = '';
    },


    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户信息采集进度";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCollectionSchedule(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCollectionSchedule(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有用户信息采集进度数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportCollectionSchedule(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    },
    getStepLabel(currentStep) {
      if (currentStep == null) return '—';
      const option = this.currentStepOptions.find(opt => opt.dictValue === currentStep);
      return option ? option.dictLabel : '未知状态';
    }
  }
};
</script>
