<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="护理时间" prop="nursingTime">
        <el-date-picker clearable
          v-model="queryParams.nursingTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择护理时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['care:clocks:add']"
        >新增</el-button>
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['care:clocks:export']"
        >导出</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="clocksList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="护理时间" align="center" prop="nursingTime" width="180">
      </el-table-column>

      <el-table-column label="图片数量" align="center" prop="imgNum" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['care:clocks:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['care:clocks:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改护理任务打卡对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="clocksRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="护理时间" prop="nursingTime">
          <el-date-picker clearable
            v-model="form.nursingTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择护理时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="图片路径" prop="imgPaths">
          <el-upload
              v-model:file-list="fileLists"
              :action="uploadImgUrl"
              :headers="uploadHeaders"
              list-type="picture-card"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style>
.app-container{
  height: 500px;
}
</style>
<script setup name="Clocks">
import { listClocks, getClocks, delClocks, addClocks, updateClocks,removeImg } from "@/api/care/clocks";
import { ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { getToken } from '@/utils/auth'
const { proxy } = getCurrentInstance();

const clocksList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const fileLists =ref([]);

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
// 定义 props
const props = defineProps({
  applyId: {
    type: String,
    required: true
  }
});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    applyId: props.applyId,
    nursingTime: null,
    imgPaths: null,
    imgNum: null,
  },
  rules: {
    nursingTime: [
      { required: true, message: "护理时间不能为空", trigger: "blur" }
    ],
    imgPaths: [
      { required: true, message: "图片路径不能为空", trigger: "blur" }
    ],
    imgNum: [
      { required: true, message: "图片数量不能为空", trigger: "blur" }
    ],
  }
});

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

const uploadImgUrl = ref(import.meta.env.VITE_APP_BASE_API + "/care/clocks/upload?applyId="+props.applyId+"&nursingDate="+form.value.nursingTime); // 上传的图片服务器地址
const uploadHeaders={Authorization: 'Bearer ' + getToken()};
const fileSize=1;

/** 查询护理任务打卡列表 */
function getList() {
  loading.value = true;
  listClocks(queryParams.value).then(response => {
    clocksList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    clockId: null,
    nursingRecordId: props.applyId,
    nursingTime: null,
    imgPaths: null,
    imgNum: null,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
    applyId:props.applyId
  };
  fileLists.value=[]
  proxy.resetForm("clocksRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.clockId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加护理任务打卡";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _clockId = row.clockId || ids.value
  getClocks(_clockId).then(response => {
    form.value = response.data;
    const imgs=response.data.imgPaths.split(",").filter(item => item.trim() !== "");
    imgs.forEach(function (item){
      console.info(item)
      const obj={};
      obj.name=''
      obj.url=import.meta.env.VITE_APP_BASE_API + item
      console.info(obj)
      fileLists.value.push(obj);
    })

    open.value = true;
    title.value = "修改护理任务打卡";
  });
}

/** 提交按钮 */
function submitForm() {
  form.value.imgNum=0;
  form.value.imgPaths=""
  console.info(import.meta.env.VITE_APP_BASE_API+"---"+JSON.stringify(fileLists.value))
  fileLists.value.forEach(item => {
    console.info(item);
    form.value.imgNum++;
    if(item.response){
      form.value.imgPaths+=item.response.imgUrl+",";
    }else{
      form.value.imgPaths+=item.url.replaceAll(import.meta.env.VITE_APP_BASE_API,"")+",";
    }

  });

  proxy.$refs["clocksRef"].validate(valid => {
    if (valid) {
      if (form.value.clockId != null) {
        updateClocks(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addClocks(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _clockIds = row.clockId || ids.value;
  proxy.$modal.confirm('是否确认删除护理任务打卡编号为"' + _clockIds + '"的数据项？').then(function() {
    return delClocks(_clockIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('care/clocks/export', {
    ...queryParams.value
  }, `clocks_${new Date().getTime()}.xlsx`)
}

function handleRemove(file, fileList) {
  console.log('移除文件:', file, '剩余文件:', fileList);
  //removeImg(file.response.imgUrl);
}

function handleBeforeUpload(file) {
  if(form.value.nursingTime==null){
    proxy.$modal.msgError('请选择护理时间!');
    return false;
  }
  const type = ["image/jpeg", "image/jpg", "image/png", "image/svg"];
  const isJPG = type.includes(file.type);
  // 检验文件格式
  if (!isJPG) {
    proxy.$modal.msgError('图片格式错误!');
    return false;
  }
  // 校检文件大小
  if (fileSize) {
    const isLt = file.size / 1024 / 1024 < fileSize;
    if (!isLt) {
      proxy.$modal.msgError(`上传文件大小不能超过 ${fileSize} MB!`);
      return false;
    }
  }
  return true;
}

function handleSuccess(response, file, fileList)
{
  if(response.code==200){
    fileLists.value=fileList;
  }

}
getList();
</script>
