<template>
  <div>
    <el-dialog title="待办事项" append-to-body v-model="dialogVisible">
      <div>
        <el-card>
          <template #header>
            <div class="flex items-center justify-between">
              <div>
                {{ props.date }} {{ getWeek(props.date) }}
                <span style="color: #e6a23c"
                  >温馨提示：您通过勾选或者取消勾选来标记事项的完成情况</span
                >
              </div>
              <div v-if="isEdit">
                <el-button
                  type="primary"
                  @click="handleAddItem"
                  :disabled="isFormerly"
                  >新增事项
                </el-button>
                <el-button type="primary" @click="handleBack"
                  >返回日历</el-button
                >
              </div>
            </div>
          </template>
          <div v-if="state.todoList?.length">
            <div
              v-for="item in state.todoList"
              :key="item.id"
              class="bg-slate-100 mb-2 relative px-2 py-3 flex items-center justify-between w-full"
            >
              <div class="flex w-full">
                <el-button
                  type="primary"
                  class="absolute top-3 right-1"
                  link
                  @click="handleEditRemark(item)"
                  >完成情况备注</el-button
                >
                <div @click="handleDone(item)" class="flex">
                  <el-icon
                    v-if="item.done"
                    style="color: #67c23a; font-size: 20px"
                    class="mr-2"
                    ><SuccessFilled
                  /></el-icon>
                  <el-icon v-else style="font-size: 20px" class="mr-2"
                    ><CircleCheck
                  /></el-icon>
                </div>
                <div class="w-9/12">
                  <el-text :tag="item.done ? 'del' : 'span'">
                    <template v-if="item.type == 2">
                      <el-text tag="b">{{ item.name }}回访</el-text>
                      <div class="mb-2" />
                      <el-text size="small" type="info"
                        >回访时需要填写：{{ item.content }}</el-text
                      >
                      <div />
                    </template>

                    <template v-else-if="item.type == 0">
                      <el-text tag="b">{{ item.name }}</el-text>
                      <div class="mb-2" />
                      <el-text size="small" type="info"
                        >检查需包含：{{ item.content }}</el-text
                      >
                    </template>
                    <template v-else>
                      <el-text tag="b">{{ item.content }}</el-text>
                    </template>
                    <div />
                    <div class="mb-2" />

                    <el-text size="small" type="info"
                      >备注：{{ item.remark || "-" }}</el-text
                    >
                  </el-text>
                  <!-- <div class="mt-2">
                    <el-input
                      v-model="item.comment"
                      placeholder="选填，输入事项完成备注信息"
                      :autosize="{ minRows: 3, maxRows: 6 }"
                      type="textarea"
                    ></el-input>
                  </div> -->
                </div>
              </div>
              <div class="flex items-center">
                <!-- <el-popconfirm
                  title="确定要删除此待办事项吗?"
                  @confirm="handleDelete(item.id)"
                >
                  <template #reference>
                    <el-button type="primary" link style="color: red">删除</el-button>
                  </template>
                </el-popconfirm> -->

                <el-popconfirm
                  @confirm="handleDelete(item)"
                  title="确定要删除这个事项吗？删除后不可恢复?"
                >
                  <template #reference>
                    <el-button
                      type="primary"
                      link
                      style="color: red"
                      class="ml-5"
                      v-if="isEdit"
                      >删除</el-button
                    >
                  </template>
                </el-popconfirm>
              </div>
            </div>
          </div>
          <div v-else>
            <el-empty />
          </div>
        </el-card>
        <el-dialog v-model="state.visibleDelete" width="30%">
          <div>
            <el-text tag="b" class="mt-2 mb-2"
              >请选择删除内容，删除后不可数据不可恢复：</el-text
            >
            <div
              class="bg-slate-100 mt-2 mb-2 p-2 flex items-center"
              @click="() => (state.currentDeleteItem = 0)"
            >
              <el-icon
                v-if="state.currentDeleteItem == 0"
                style="font-size: 20px; color: #67c23a"
                class="mr-2"
                ><SuccessFilled
              /></el-icon>
              <span v-else class="dot mr-2" />
              <div>
                <div>
                  {{ props.date }}
                  <span v-if="props.date == state.currentItem.endDate"
                    >（当天）</span
                  >
                  <div>{{ state.currentItem.content }}</div>
                </div>
              </div>
            </div>

            <div
              class="bg-slate-100 mb-2 p-2 flex items-center"
              @click="() => (state.currentDeleteItem = 1)"
            >
              <el-icon
                v-if="state.currentDeleteItem == 1"
                style="font-size: 20px; color: #67c23a"
                class="mr-2"
                ><SuccessFilled
              /></el-icon>
              <span class="dot mr-2" v-else />
              <div>
                <div>
                  {{ props.date }} 至
                  {{ state.currentItem?.endDate }}

                  <span v-if="props.date == state.currentItem.endDate"
                    >（当天）</span
                  >
                  <span v-else> (当天起至往后)</span>
                </div>
                <div>
                  每{{ ["天", "周", "月", "天"][state.currentItem?.type || 0]
                  }}{{ state.currentItem.content }}
                </div>
              </div>
            </div>

            <div
              class="bg-slate-100 mb-2 p-2 flex items-center"
              @click="() => (state.currentDeleteItem = 2)"
            >
              <el-icon
                v-if="state.currentDeleteItem == 2"
                style="font-size: 20px; color: #67c23a"
                class="mr-2"
                ><SuccessFilled
              /></el-icon>
              <span class="dot mr-2" v-else />
              <div>
                <div>
                  {{ state.currentItem?.startDate }} 至
                  {{ state.currentItem?.endDate }} (所有时间)
                </div>
                <div>
                  每{{ ["天", "周", "月", "天"][state.currentItem?.type]
                  }}{{ state.currentItem.content }}
                </div>
              </div>
            </div>
            <div class="text-right">
              <el-button @click="() => (state.visibleDelete = false)"
                >取消</el-button
              >
              <el-popconfirm
                @confirm="handleDeleteItem(index)"
                title="确定要删除这个事项吗？删除后不可恢复?"
              >
                <template #reference>
                  <el-button type="primary">确定</el-button>
                </template>
              </el-popconfirm>
            </div>
          </div>
          <div />
        </el-dialog>
      </div>
    </el-dialog>
    <ComponentDialogSetMatter
      v-model:show="state.visibleTable"
      :date="props.date"
      @save="onSave"
    />
    <el-dialog
      append-to-body
      title="完成情况备注"
      v-model="state.visibleRemark"
    >
      <div class="mt-2">
        <el-input
          v-model="state.rowData.comment"
          placeholder="选填，输入事项完成备注信息"
          :autosize="{ minRows: 6, maxRows: 10 }"
          type="textarea"
        />
      </div>
      <template #footer>
        <el-button type="primary" plain @click="state.visibleRemark = false"
          >取消</el-button
        >
        <el-button type="primary" @click="onSaveRemark()">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { request, getWeek } from "@/utils";

import { ref, computed, defineProps, defineEmits, watch, reactive } from "vue";
import { SuccessFilled, CircleCheck } from "@element-plus/icons-vue";
import ComponentDialogSetMatter from "./DialogSetMatter.vue";
import { useManageProjectStoreHook } from "@/store/modules/manageProject";
import { ElMessage } from "element-plus";
import moment from "moment";
const currentArchiveId = computed(() => {
  return useManageProjectStoreHook()?.currentArchiveId;
});
const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  date: {
    type: String,
    default: ""
  },
  rowData: {
    type: Object,
    default: () => {}
  },
  type: {
    type: String,
    default: "edit"
  }
});
const emits = defineEmits(["update:show", "success"]);
const isEdit = computed(() => {
  return props.type == "edit";
});
const dialogVisible = computed({
  get() {
    return props.show;
  },
  set(n) {
    emits("update:show", n);
  }
});

watch(
  () => dialogVisible.value,
  n => {
    if (n) {
      getTodoList();
    } else {
    }
  }
);

// 是否过了今日的时间
const isFormerly = computed(() => {
  return moment(props.date).diff(moment(), "days") < 0;
});

const state = reactive({
  visibleTable: false,
  todoList: [],
  currentItem: [],
  currentDeleteItem: 0,
  visibleDelete: false,
  visibleRemark: false,
  rowData: {
    comment: ""
  }
});
const handleAddItem = () => {
  state.visibleTable = true;
};
const handleEditRemark = item => {
  state.rowData = item;
  state.visibleRemark = true;
};
const onSave = tableData => {
  const params = tableData.map(v => {
    return {
      ...v,
      archiveId: currentArchiveId.value,
      duration: Number(v.duration),
      date: props.date
    };
  });
  request
    .post("/platformApi/dataService/diseaseManage/todos", {
      todos: params
    })
    .then(resp => {
      ElMessage.success(resp.message);
      dialogVisible.value = false;
      emits("success");
    });
};
const getTodoList = () => {
  request
    .get("/platformApi/dataService/diseaseManage/todoList/duration", {
      params: {
        archiveId: currentArchiveId.value,
        startDate: props.date,
        endDate: props.date
      }
    })
    .then(resp => {
      state.todoList = resp.data[0]?.checkItems?.map(v => {
        return {
          visible: false,
          comment: "",
          ...v
        };
      });
    });
};
const handleDone = item => {
  request
    .post("/platformApi/dataService/diseaseManage/checkTodo", {
      id: item.id,
      date: props.date,
      status: item.done ? 0 : 1
    })
    .then(resp => {
      ElMessage.success(resp.message);
      getTodoList();
      emits("success");
    });
};
const handleDelete = item => {
  state.currentDeleteItem = 0; //恢复默认值
  state.currentItem = item;
  // state.visibleDelete = true;
  handleDeleteItem();
};
const handleDeleteItem = index => {
  request
    .post("/platformApi/dataService/diseaseManage/delete/todo", {
      id: state?.currentItem?.id,
      date: props.date,
      type: state.currentDeleteItem
    })
    .then(resp => {
      getTodoList();
      // state.todoList[index] = false;
      ElMessage.success(resp?.message);
      emits("success");
      // state.visibleDelete = false;
    });
};
const onSaveRemark = () => {
  const item = state.rowData;
  request
    .post("/platformApi/dataService/diseaseManage/todo/comment", {
      id: item.id,
      date: props.date,
      comment: item.comment
    })
    .then(resp => {
      ElMessage.success(resp.message);
      getTodoList();
      state.visibleRemark = false;
    });
};
const handleBack = () => {
  dialogVisible.value = false;
};
</script>
<style scoped lang="scss">
.dot {
  width: 20px;
  height: 20px;
  border: 1px solid #ddd;
  border-radius: 50%;
}
</style>
