<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--诊疗目录-->
      <el-col :span="4" :xs="24">
        <div class="head-title">频次字典</div>
        <div>
          <el-table
            ref="freTableRef"
            v-loading="loading"
            :data="frequency"
            row-key="id"
            @row-click="handleRowClick"
        >
           <el-table-column label="字典频次名称" align="left" prop="dictLabel" />
            <el-table-column label="字典频次代码" align="left" prop="dictValue" />
          </el-table>
          <pagination
              v-show="frequencyTotal > 0"
              :total="frequencyTotal"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              @pagination="getFrequencyList"
          />
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
                type="primary"
                plain
                icon="Plus"
                @click="openDialog"
                v-hasPermi="['system:user:add']"
            >添加频次详情</el-button
            >
          </el-col>
        </el-row>

        <el-table
            v-loading="loading"
            :data="frequencyDetail"
        >
          <!-- 定义表格列 -->
          <el-table-column
              prop="rateCode"
              label="频次代码"
              width="180">
          </el-table-column>

          <el-table-column
              prop="name"
              label="名称"
              width="200">
          </el-table-column>

          <el-table-column
              prop="dayCount"
              label="每天执行次数"
              width="120">
          </el-table-column>

<!--          <el-table-column-->
<!--              prop="dayInterval"-->
<!--              label="每次执行间隔（天数）"-->
<!--              width="180">-->
<!--          </el-table-column>-->

          <el-table-column
              prop="dayTimes"
              label="执行时间点"
              width="300">
          </el-table-column>

<!--          <el-table-column-->
<!--              prop="weekCycleFlag"-->
<!--              label="是否周期性每周执行"-->
<!--              width="150">-->
<!--            <template #default="scope">-->
<!--              {{ scope.row.weekCycleFlag === 1 ? '是' : '否' }}-->
<!--            </template>-->
<!--          </el-table-column>-->

<!--          <el-table-column-->
<!--              prop="weekInterval"-->
<!--              label="每周执行的间隔"-->
<!--              width="150">-->
<!--          </el-table-column>-->

<!--          <el-table-column-->
<!--              prop="weekTimes"-->
<!--              label="每周执行的次数"-->
<!--              width="120">-->
<!--          </el-table-column>-->

<!--          <el-table-column-->
<!--              prop="continueFlag"-->
<!--              label="是否为连续执行"-->
<!--              width="150">-->
<!--            <template #default="scope">-->
<!--              {{ scope.row.continueFlag === 1 ? '是' : '否' }}-->
<!--            </template>-->
<!--          </el-table-column>-->

          <el-table-column
              prop="totalExecutionCount"
              label="执行总次数"
              width="120">
          </el-table-column>

          <el-table-column
              prop="executionPeriod"
              label="执行周期长度"
              width="150">
          </el-table-column>

          <el-table-column
              prop="executionPeriodUnit"
              label="执行周期单位"
              width="150">
          </el-table-column>
<!--          <el-table-column-->
<!--              prop="memo"-->
<!--              label="备注信息"-->
<!--              width="200">-->
<!--          </el-table-column>-->
          <el-table-column
              label="操作"
              align="center"
              width="150"
              class-name="small-padding fixed-width"
              fixed="right"
          >
            <template #default="scope">
              <el-button
                  link
                  type="primary"
                  icon="Edit"
                  @click="openSave(scope.row, scope.$index)"
                  v-hasPermi="['system:user:edit']"
              >编辑</el-button
              >
              <el-button
                  type="danger"
                  link
                  icon="Delete"
                  :disabled="scope.row.id == ''"
                  @click="deleteSelectedRows(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
<!--        <pagination-->
<!--            v-show="frequencyDetailTotal > 0"-->
<!--             :total="frequencyDetailTotal"-->
<!--            v-model:page="queryDetailParams.pageNum"-->
<!--            v-model:limit="queryDetailParams.pageSize"-->
<!--            @pagination="getDetailList"-->
<!--        />-->
      </el-col>
    </el-row>
    <FreForm
        v-model="dialogVisible"
        :initialFormData="showFormData"
        @submit="handleFormSubmit"
    />
  </div>
</template>

<script setup name="frequency">
import {
  addFrequencyDetail, deleteFrequencyDetail,
  getFrequencyDetailList
} from './components/frequency.js';
import { ElMessage } from "element-plus";
import {
  listData
} from "@/api/system/dict/data.js";
import FreForm from "@/views/basicmanage/frequency/components/FreForm.vue";
const frequency = ref([]);
const frequencyDetail = ref([]);
const frequencyTotal = ref(0);
const frequencyDetailTotal = ref(0);
const currentLeftRow = ref(null);
let addFlag = ref(true);
const data = reactive({
  form: {},
  queryParams: {
    dictType: 'rate_code',
    status : 0,
    pageNum: 1,
    pageSize: 10,
  },
  queryDetailParams: {
    code: '',
    status : 0,
    pageNum: 1,
    pageSize: 10,
  }
});
const dialogVisible = ref(false);
const showFormData   = ref({});            // 真正给弹窗用的数据
// 初始表单数据

const { queryParams, form, tableRules,queryDetailParams } = toRefs(data);

/** 获取字典列表 */
function getFrequencyList() {
  listData(queryParams.value).then((res) => {
    if (res.code === 200) {
      frequency.value =
          res.rows.length > 0
              ? res.rows.map((res) => {
                return {
                  ...res,
                  isEditing: false, // 标记当前行是否正在编辑
                  error: false, // 新增 error 字段
                };
              })
              : [];
    }
    frequencyTotal.value = res.total;
  });
}
function getDetailList() {
  getFrequencyDetailList(queryDetailParams.value).then((res) => {
    if (res.code === 200) {
      frequencyDetail.value =
          res.data.records.length > 0
              ? res.data.records.map((record) => {
                // 将 dayTimes 字符串转换为数组
                const dayTimesArray = record.dayTimes.split(',');
                const sortedDayTimesArray = dayTimesArray.sort((a, b) => {
                  const timeToMinutes = (time) => {
                    const [hours, minutes] = time.split(':').map(Number);
                    return hours * 60 + minutes;
                  };
                  return timeToMinutes(a) - timeToMinutes(b);
                });
                const sortedDayTimesString = sortedDayTimesArray.join(',');
                return {
                  ...record,
                  dayTimes: sortedDayTimesString, // 使用排序后的字符串
                  error: false, // 新增 error 字段
                };
              })
              : [];
    }
    if( res.data.records.length > 0){
      //有数据不允许添加
      addFlag.value = false;
    }else{
      addFlag.value = true;
    }
    frequencyDetailTotal.value = res.data.total;
  });
}
/** 节点单击事件 */
function handleRowClick(row) {
  queryDetailParams.value.code = row.dictValue;
  currentLeftRow.value = row;        // 记录当前行
  getDetailList();

}
function openDialog() {
  if (!currentLeftRow?.value) {
    ElMessage.warning('请先选择一行字典数据！')
    return;
  }
  if (addFlag.value === false) {
    ElMessage.warning('已有详情！请直接修改！')
    addFlag.value = true;
    return;
  }
  //默认显示数据
  showFormData.value = {
    rateCode: currentLeftRow.value.dictValue,
    name : currentLeftRow.value.dictLabel,
    dayCount: 0,
    dayInterval: 0,
    dayTimes: [],
    weekCycleFlag: 0,
    weekInterval: 0,
    weekTimes: 0,
    continueFlag: 0,
    totalExecutionCount: 0,
    executionPeriod: 0,
    executionPeriodUnit: 'day',
    memo: ''
  };
  dialogVisible.value = true;
}
// 处理表单提交
/* 保存/新增 */
function handleFormSubmit(initialFormData) {

  addFrequencyDetail(initialFormData).then(() => {
    getDetailList();
    ElMessage.success('保存成功');
  });
}

function openSave(row) {
  //默认显示数据
  showFormData.value = { ...row };
  row.dayTimes = row.dayTimes.split(',');
  row.dayTimes.sort((a, b) => {
    // 将时间字符串转换为分钟数进行比较
    const timeToMinutes = (time) => {
      const [hours, minutes] = time.split(':').map(Number);
      return hours * 60 + minutes;
    };

    return timeToMinutes(a) - timeToMinutes(b);
  });
  // 更新 showFormData 中的 dayTimes
  showFormData.value.dayTimes = row.dayTimes;

  dialogVisible.value = true;
}


/* 删除 */
function deleteSelectedRows(row) {
   deleteFrequencyDetail(row.id).then(() => {
    ElMessage.success('删除成功');
    getDetailList();
  });
}

getFrequencyList();

</script>
<style scoped>
.el-form--inline .el-form-item {
  display: inline-flex;
  vertical-align: middle;
  margin-right: 10px !important;
}
.error-border {
  border: 1px solid red;
}
</style>
