<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item :label="tLang('pms','执行单编码')" prop="checkCode">
        <el-input v-model="queryParams.checkCode" :placeholder="tLang('common','请输入') + tLang('pms','执行单编码')" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <!-- <el-form-item :label="tLang('','')实际保养时间" prop="checkTime">
        <el-date-picker clearable v-model="queryParams.checkTime" type="date" value-format="YYYY-MM-DD"
          :placeholder="tLang('common','请选择') + tLang('','')实际保养时间">
        </el-date-picker>
      </el-form-item> -->
      <el-form-item :label="tLang('pms','计划编码')" prop="checkPlanCode">
        <el-input v-model="queryParams.checkPlanCode" :placeholder="tLang('common','请输入') + tLang('pms','计划编码')" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item :label="tLang('pms','执行人')" prop="checkUser">
        <el-input v-model="queryParams.checkUser" :placeholder="tLang('common','请输入') + tLang('pms','执行人')" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item :label="tLang('pms','计划类型')" prop="planType">
        <el-select v-model="queryParams.planType" :placeholder="tLang('common','请选择') + tLang('pms','计划类型')" clearable @change="handleQuery">
          <el-option v-for="item in pms_plan_type" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">{{ tLang('common', '搜索') }}</el-button>
        <el-button icon="Refresh" @click="resetQuery">{{ tLang('common', '重置') }}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['pms:checkRecord:edit']">{{ $t('common.修改') }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['pms:checkRecord:remove']">{{ $t('common.删除') }}</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="checkRecordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column :label="tLang('common','序号')" align="center" type="index" width="60" />
      <el-table-column :label="tLang('pms','执行单编码')" align="center" prop="checkCode" />
      <!-- <el-table-column :label="tLang('','')保养项目集合" align="center" prop="subjectCodes" /> -->
      <el-table-column :label="tLang('pms','计划编码')" align="center" prop="checkPlanCode" width="200">
        <template #default="scope">
          <el-button type="text" @click="handleView(scope.row)">{{
      scope.row.checkPlanCode }}</el-button>
        </template>
      </el-table-column>
      <el-table-column :label="tLang('pms','计划类型')" align="center" prop="planType">
        <template #default="scope">
          <dict-tag :options="pms_plan_type" :value="scope.row.planType" />
        </template>
      </el-table-column>
      <el-table-column :label="tLang('pms','实际执行时间')" align="center" prop="checkTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.checkTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="tLang('pms','执行人')" align="center" prop="checkUser" />
      <el-table-column :label="tLang('pms','计划执行时间')" align="center" prop="nextCheckTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.nextCheckTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="tLang('pms','最晚执行时间')" align="center" prop="deadline" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.deadline, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="tLang('pms','执行提醒')" align="center" prop="" width="180">
        <template #default="scope">
          <el-tag v-if="scope.row.status == 1" :type="deadlineFun(scope)['color']">{{ deadlineFun(scope)['text'] }}</el-tag>
          
        </template>
      </el-table-column>
      <el-table-column :label="tLang('common','状态')" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="scope.row.status == 1 ? 'info' : scope.row.status == 2 ? 'success' : 'danger'">
            {{ scope.row.status == 1 ? tLang('pms','待执行') : scope.row.status == 2 ? tLang('common','完成') : tLang('common','延期') }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column :label="tLang('','')文件" align="center" prop="file" /> -->
      <el-table-column :label="tLang('common','备注')" align="center" prop="remark" />
      <el-table-column :label="tLang('common','操作')" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['pms:checkRecord:edit']">{{ scope.row.status == 1 ? tLang('common','修改') : tLang('common','查看') }}</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['pms:checkRecord:remove']">{{tLang('common','删除')}}</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="800px" append-to-body>
      <el-form ref="checkRecordRef" :model="form" :rules="rules" label-width="140px">
        <el-form-item :label="tLang('pms','执行单编码')" prop="checkCode">
          <el-input v-model="form.checkCode" disabled />
        </el-form-item>
        <el-form-item :label="tLang('pms','实际执行时间')" prop="checkTime">
          <el-date-picker clearable v-model="form.checkTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            :placeholder="tLang('common','请选择') + tLang('pms','实际执行时间')">
          </el-date-picker>
        </el-form-item>
        <!-- <el-form-item :label="tLang('pms','')保养项目集合" prop="subjectCodes">
          <el-input v-model="form.subjectCodes" placeholder="请输入保养项目集合" />
        </el-form-item> -->
        <el-form-item :label="tLang('pms','计划编码')" prop="checkPlanCode">
          <el-input v-model="form.checkPlanCode" disabled :placeholder="tLang('common','请输入') + tLang('pms','计划编码')" />
        </el-form-item>
        <el-form-item :label="tLang('pms','执行人')" prop="checkUser">
          <el-input v-model="form.checkUser" :placeholder="tLang('common','请输入') + tLang('pms','执行人')" />
        </el-form-item>
        <el-form-item :label="tLang('pms','计划执行时间')" prop="nextCheckTime">
          <el-date-picker clearable v-model="form.nextCheckTime" disabled type="date" value-format="YYYY-MM-DD">
          </el-date-picker>
        </el-form-item>
        <el-form-item :label="tLang('pms','最晚执行时间')" prop="deadline">
          <el-date-picker clearable v-model="form.deadline" disabled type="date" value-format="YYYY-MM-DD">
          </el-date-picker>
        </el-form-item>
        <el-form-item :label="tLang('common','文件')" prop="file">
          <file-upload v-model="form.file" />
        </el-form-item>
        <el-form-item :label="tLang('common','备注')" prop="remark">
          <el-input v-model="form.remark" type="textarea" :placeholder="tLang('common','请输入') + tLang('common','备注')" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" v-if="form.status === 1" @click="submitForm">{{tLang('common','确 定')}}</el-button>
          <el-button @click="cancel">{{tLang('common','取 消')}}</el-button>
        </div>
      </template>
    </el-dialog>
    <CheckplanTemp :form="checkplanForm" v-model="checkplanTempOpen" />
  </div>
</template>

<script setup name="CheckRecord">
import CheckplanTemp from "./checkplanTemp.vue"
import { listCheckRecord, getCheckRecord, updateCheckRecord, delCheckRecord } from "@/api/pms/checkplan";
import { getCheckplan } from "@/api/pms/checkplan";

const { proxy } = getCurrentInstance();
const { pms_cycle_type, pms_order_status, pms_plan_type } = proxy.useDict("pms_cycle_type", "pms_order_status", "pms_plan_type");

const checkRecordList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(false);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const checkplanTempOpen = ref(false);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    checkCode: null,
    checkPlanCode: null,
    checkUser: null,
    planType: null,
  },
  rules: {
    checkTime: [{ required: true, message: proxy.tLang('common','请选择') + proxy.tLang('pms','实际执行时间'), trigger: "blur" },
    //开始时间不能大于结束时间
    { validator: validateStarttime, trigger: 'change' }],
  }
});

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

/** 查询保养记录列表 */
function getList() {
  loading.value = true;
  listCheckRecord(queryParams.value).then(response => {
    checkRecordList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

//时间验证
function validateStarttime(rule, value, callback) {
    let checkTime = new Date(form.value.checkTime).getTime();
    let NowTime = new Date().getTime();
    if (checkTime > 0 && checkTime>NowTime) {
        callback(new Error('实际执行时间不能超过当前时间'));
    } else {
        callback();
    }
    // if (start > 0 && end > 0 && start > end) {
    //     callback(new Error('开始时间不能大于结束时间'));
    // } else {
    //     callback();
    // }
}

/**
 * 计算剩余天数
 */
function deadlineFun(scope) {
  const now = new Date().getTime();
  const nextCheckTime = new Date(scope.row.nextCheckTime).getTime();
  const deadline = new Date(scope.row.deadline).getTime();
  let color = 'success';
  let diff = 0;
  let day = 0;
  if (now < nextCheckTime) {
    diff = nextCheckTime - now;
    day = '剩余'+Math.floor(diff / (24 * 3600 * 1000));
  } else if(now > nextCheckTime && now < deadline) {
    diff = deadline - now;
    day = '剩余'+Math.floor(diff / (24 * 3600 * 1000));
    color = 'warning';
  } else {
    diff = now - deadline;
    color = 'danger';
    day = '已延期'+Math.floor(diff / (24 * 3600 * 1000));
  }

  return {
    color:color,
    text: day + '天'
  };
}

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

// 表单重置
function reset() {
  form.value = {
    id: null,
    checkCode: null,
    checkTime: null,
    subjectCodes: null,
    checkPlanCode: null,
    checkUser: null,
    nextCheckTime: null,
    deadline: null,
    createTime: null,
    status: null,
    file: null,
    remark: null
  };
  proxy.resetForm("checkRecordRef");
}

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

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

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
const checkplanForm = ref({});
//查看保养单
function handleView(row) {
  getCheckplan(row.planId).then(response => {
    checkplanForm.value = response.data;
    checkplanTempOpen.value = true;
  });
}

/** 新增按钮操作 */
// function handleAdd() {
//   reset();
//   open.value = true;
//   title.value = "添加保养记录";
// }

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getCheckRecord(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改保养记录";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["checkRecordRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateCheckRecord(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCheckRecord(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除保养记录编号为"' + _ids + '"的数据项？').then(function () {
    return delCheckRecord(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

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

getList();
</script>
