<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item :label="tLang('pms','计划编码')" prop="planCode">
        <el-input v-model="queryParams.planCode" :placeholder="tLang('common', '请输入') + tLang('pms', '计划编码')" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item :label="tLang('pms','计划名称')" prop="planName">
        <el-input v-model="queryParams.planName" :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>
          <el-option v-for="dict in pms_plan_type" :key="dict.value" :label="tLang('pms',dict.label)" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item :label="tLang('common','状态')" prop="status">
        <el-select v-model="queryParams.status" :placeholder="tLang('common', '请选择') + tLang('common', '状态')" clearable>
          <el-option key="PREPARE" :label="tLang('pms','草稿')" value="PREPARE" />
          <el-option key="FINISHED" :label="tLang('common','已完成')" value="FINISHED" />
        </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="primary" plain icon="plus" @click="handleAdd"
          v-hasPermi="['mes:dv:checkplan:add']">{{ $t('common.新增') }}</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['mes:dv:checkplan:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['mes:dv:checkplan:remove']">删除</el-button>
      </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="checkplanList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column :label="tLang('pms','计划编码')" align="center" prop="planCode">
        <template #default="scope">
          <el-button type="text" @click="handleView(scope.row)" v-hasPermi="['mes:dv:checkplan:query']">{{
      scope.row.planCode }}</el-button>
        </template>
      </el-table-column>
      <el-table-column :label="tLang('pms','计划名称')" align="center" width="200px" prop="planName" />
      <el-table-column :label="tLang('pms','计划类型')" align="center" width="120px" 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="startDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="tLang('pms','结束日期')" align="center" prop="endDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="tLang('pms','频率')" align="center" prop="cycleType">
        <template #default="scope">
          {{ scope.row.cycleCount }}
          <dict-tag :options="pms_cycle_type" :value="scope.row.cycleType" />
        </template>
      </el-table-column>
      <el-table-column :label="tLang('common','状态')" align="center" key="status">
        <template #default="scope">
          <el-switch v-model="scope.row.status" :active-value="0" :inactive-value="1"
            @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column :label="tLang('common','操作')" align="center" width="130px" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button size="small" type="text" icon="edit" @click="handleUpdate(scope.row)"
            v-if="scope.row.status == '1'" v-hasPermi="['mes:dv:checkplan:edit']">{{ tLang('common', '修改') }}</el-button>
          <el-button size="small" type="text" icon="delete" @click="handleDelete(scope.row)"
            v-if="scope.row.status == '1'" v-hasPermi="['mes:dv:checkplan:remove']">{{tLang('common', '删除')}}</el-button>
          <!-- <el-button size="small" type="text" icon="stopwatch" @click="handleUpdate(scope.row)"
            v-if="scope.row.status == 'FINISHED'" v-hasPermi="['mes:dv:checkplan:edit']">停用</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="title" v-model="open" width="960px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px"
        :disabled="optType == 'view' || form.status == 'FINISHED'">
        <el-row>
          <el-col :span="8">
            <el-form-item :label="tLang('pms','计划编码')" prop="planCode">
              <el-input v-model="form.planCode" :placeholder="tLang('common', '请输入') + tLang('pms', '计划编码')" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <!-- <el-form-item label-width="10">
              <el-switch v-model="autoGenFlag" active-color="#13ce66" active-text="自动生成"
                @change="handleAutoGenChange(autoGenFlag)" v-if="optType != 'view'&&optType != 'edit'">
              </el-switch>
            </el-form-item> -->
          </el-col>
          <el-col :span="12">
            <el-form-item :label="tLang('pms','计划名称')" prop="planName">
              <el-input v-model="form.planName" :placeholder="tLang('common', '请输入') + tLang('pms', '计划名称')" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="tLang('pms','计划类型')" prop="planType">
              <el-select v-model="form.planType" :placeholder="tLang('common', '请选择') + tLang('pms', '计划类型')" @change="changePlanType">
                <el-option v-for="dict in pms_plan_type" :key="dict.value" :label="tLang('pms', dict.label)"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="tLang('pms','频率')" prop="cycleCount">
              <el-input-number :min="1" :step="1" v-model="form.cycleCount" :placeholder="tLang('common', '请输入') + tLang('pms', '频率')" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item prop="cycleType" label-width="00">
              <el-select v-model="form.cycleType" >
                <el-option v-for="dict in pms_cycle_type" :key="dict.value" :label="tLang('pms', dict.label)"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item :label="tLang('device','设备名称')" prop="deviceId">
              <!-- <el-input v-model="form.deviceId" :placeholder="请选择设备" disabled>
                                <el-button style="border-color: #46a6ff; background-color: #46a6ff;color: white;"
                                    slot="append" @click="handleMachineryAdd" icon="el-icon-search"></el-button>
                            </el-input> -->
              <el-select v-model="form.deviceId" ::placeholder="tLang('common', '请选择') + tLang('device', '设备')">
                <el-option v-for="item in deviceList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <!-- <el-form-item label="设备名称" prop="machineryName">
              <el-input v-model="form.machineryName" :placeholder="请选择设备" disabled />
            </el-form-item> -->
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="执行人" prop="checkUser">
              <el-input v-model="form.checkUser" :placeholder="请输入执行人" />
              
            </el-form-item>
          </el-col> -->
          <!-- <el-select v-model="form.checkUser" filterable
                ::placeholder="tLang('common', '请选择') + tLang('produce', '执行人')" style="width: 240px">
                <el-option v-for="item in userList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select> -->
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item :label="tLang('pms','开始日期')" prop="startDate">
              <el-date-picker clearable v-model="form.startDate" type="date" value-format="YYYY-MM-DD"
                :placeholder="tLang('common', '请选择') + tLang('pms', '开始日期')">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="tLang('pms','结束日期')" prop="endDate">
              <el-date-picker clearable v-model="form.endDate" type="date" value-format="YYYY-MM-DD"
                :placeholder="tLang('common', '请选择') + tLang('pms', '结束日期')">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="8">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" disabled>
                <el-option v-for="dict in pms_order_status" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item :label="tLang('device','备注')" prop="remark">
              <el-input v-model="form.remark" type="textarea" :placeholder="tLang('common', '请输入') + tLang('device', '备注')" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-tabs type="border-card">
        <el-tab-pane :label="form.planType == 'CHECK' ? tLang('pms','点检') : tLang('pms','保养')">
          <Checksubject ref="subjectlist" :subjectList="subjectList" :checksubjectList="form.subjects"
            :checkstatus="form.status" :optType="optType"></Checksubject>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm"
            v-if="form.status == 1 && optType != 'view'">{{ tLang('common','保存') }}</el-button>
          <!-- <el-button type="success" @click="handleFinish"
            v-if="form.status == 1 && optType != 'view' && form.id != null">启用</el-button>
          <el-button type="success" @click="handleDeFinish"
            v-if="form.status == 0 && optType != 'view' && form.id != null">停用</el-button> -->
          <el-button @click="cancel">{{tLang('common','取 消')}}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from "vue";
import { listCheckplan, getCheckplan, delCheckplan, addCheckplan, updateCheckplan,changeCheckplanStatus } from "@/api/pms/checkplan";
import { listDvsubject } from "@/api/pms/dvsubject";
import { listDevice } from "@/api/pms/device.js";
import Checksubject from "./subject.vue"
import { listUser } from "@/api/system/user";
import { genCode } from "@/api/system/autocode/rule"

const { proxy } = getCurrentInstance()
const { pms_cycle_type, pms_order_status, pms_plan_type } = proxy.useDict("pms_cycle_type", "pms_order_status", "pms_plan_type");
let autoGenFlag = ref(false)
let optType = ref(undefined)
// 遮罩层
let loading = ref(true)
// 选中数组
let ids = ref([])
// 非单个禁用
let single = ref(true)
// 非多个禁用
let multiple = ref(true)
// 显示搜索条件
let showSearch = ref(false)
// 总条数
let total = ref(0)
// 设备点检计划头表格数据
let checkplanList = ref([])
// 弹出层标题
let title = ref("")
// 是否显示弹出层
let open = ref(false)
// 查询参数
let queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  planCode: null,
  planName: null,
  startDate: null,
  endDate: null,
  cycleType: null,
  cycleCount: null,
  status: null
})
// 表单参数
let form = ref({})
let formRef = ref(null)

let deviceList = ref([])
// 表单校验
let rules = {
  planCode: [
    { required: true, message: proxy.tLang('pms','计划编码') + proxy.tLang('common','不能为空'), trigger: "blur" }
  ],
  planName: [
    { required: true, message: proxy.tLang('pms','计划名称')+ proxy.tLang('common','不能为空'), trigger: "blur" }
  ],
  planType: [
    { required: true, message: proxy.tLang('pms','计划类型')+ proxy.tLang('common','不能为空'), trigger: "blur" }
  ],
  deviceId: [
    { required: true, message: proxy.tLang('common','请选择') + proxy.tLang('device','设备'), trigger: "blur" }
  ],
  cycleType: [
    { required: true, message: proxy.tLang('common','请选择') + proxy.tLang('pms','频率'), trigger: "blur" }
  ],
  cycleCount: [
    { required: true, message: proxy.tLang('common','请输入') + proxy.tLang('pms','次数'), trigger: "blur" }
  ],
  startDate: [
    { required: true, message: proxy.tLang('common','请选择') + proxy.tLang('pms','开始日期'), trigger: "blur" },
    //开始时间不能大于结束时间
    { validator: validateStarttime, trigger: 'change' }
  ],
  endDate: [
    { required: true, message:proxy.tLang('common','请选择') + proxy.tLang('pms','结束日期'), trigger: "blur" },
    //开始时间不能大于结束时间
    { validator: validateStarttime, trigger: 'change' }
  ],
}

const userList = ref([])

// 初始化下拉框数据
function selectListInit() {

  listUser({ pageSize: 1000 }).then(response => {
    userList.value = response.rows.map(item => {
      return {
        value: item.userId,
        label: item.nickName + '_' + item.code
      };
    })
  });

}

function validateStarttime(rule, value, callback) {
  let start = new Date(form.value.startDate).getTime();
  let end = new Date(form.value.endDate).getTime();
  if (start > 0 && end > 0 && start > end) {
    callback(new Error(proxy.tLang('validate','开始日期不能大于结束日期')));
  } else {
    callback();
  }

}

/** 查询设备点检计划头列表 */
function getList() {
  loading.value = true;
  listCheckplan(queryParams).then(response => {
    checkplanList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

//获取设备列表
function getDeviceList() {
  listDevice({ pageSize: 100 }).then(response => {
    deviceList.value = response.rows.map(item => {
      return {
        value: item.id + '',
        label: item.name,
        brand: item.brand,
      }
    })
  })
}
let subjectList = ref([]);
// 点检保养项目列表
function getListDvsubject(subjectType) {
  listDvsubject({ pageSize: 100, subjectType }).then(response => {
    subjectList.value = response.rows.map(item => {
      return {
        value: item.subjectCode,
        label: item.subjectName,
        subjectCode: item.subjectCode,
        subjectName: item.subjectName,
        subjectType: item.subjectType,
        subjectContent: item.subjectContent,
        subjectStandard: item.subjectStandard
      };
    });
  });
}
let checksubjectList = ref([]);

//改变计划类型
function changePlanType(e) {
  getListDvsubject(e);
  form.value.subjects = [];
}

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

// 表单重置
function reset() {
  form.value = {
    id: null,
    planCode: null,
    planName: null,
    planType: null,
    startDate: null,
    endDate: null,
    cycleType: null,
    cycleCount: null,
    status: 1,
    remark: null,
    attr1: null,
    attr2: null,
    attr3: null,
    attr4: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    subjectCodes: [],
    deviceId: null,
    subjects: []
  }
  autoGenFlag.value = false;
  proxy.resetForm("formRef");
}

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

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryForm");
  handleQuery();
}
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = proxy.tLang('common','添加')+ proxy.tLang('pms','计划');
  optType.value = "add";
  handleAutoGenChange(true)
}

// 查询明细按钮操作
function handleView(row) {
  reset();
  const id = row.id || ids.value;
  getCheckplan(id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = proxy.tLang('common','查看')+ proxy.tLang('pms','计划');
    optType.value = "view";
  });
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value
  getCheckplan(id).then(response => {
    form.value = response.data;
    getListDvsubject(response.data.planType)
    if (form.value.subjects&&form.value.subjects.length > 0) {
      form.value.subjectCodes = form.value.subjects.map(item => item.subjectCode);
    } else {
      form.value.subjectCodes = [];
    }

    open.value = true;
    title.value = proxy.tLang('common','修改')+ proxy.tLang('pms','计划');
    optType.value = "edit";
  });
}

/** 点检保养状态修改  */
function handleStatusChange(row) {
  let text = row.status === 0 ? proxy.tLang('common','启用') : proxy.tLang('common','停用');
  proxy.$modal.confirm(proxy.tLang('tip','确定要') + text + ' "' + row.planCode + '"?').then(function () {
    return changeCheckplanStatus(row.id, row.status);
  }).then(() => {
    proxy.$modal.msgSuccess(text + proxy.tLang('common','成功'));
  }).catch(function () {
    row.status = row.status === 0 ? 1 : 0;
  });
};

/** 提交按钮 */
function submitForm() {
  formRef.value.validate(valid => {
    if (valid) {
      if (form.value.subjects&&form.value.subjects.length > 0) {
      form.value.subjectCodes = form.value.subjects.map(item => item.subjectCode).join(",");
    } else {
      form.value.subjectCodes = '';
    }
      if (form.value.id != null) {
        updateCheckplan(form.value).then(response => {
          proxy.$modal.msgSuccess(proxy.tLang('common', '修改成功'));
          open.value = false;
          getList();
        });
      } else {
        addCheckplan(form.value).then(response => {
          proxy.$modal.msgSuccess(proxy.tLang('common', '新增成功'));
          open.value = false;
          getList();
        });
      }
    }
  });
}

function handleFinish() {
  if (form.value.id != null && form.value.status == 'PREPARE') {
    form.value.status = 'FINISHED';
    form.value.subjectCodes = form.value.subjects.map(item => item.subjectCode).join(",");
    updateCheckplan(form.value).then(response => {
      proxy.$modal.msgSuccess(proxy.tLang('common', '已启用'));
      open.value = false;
      getList();
    }, err => {
      form.value.status = 'PREPARE';
    });
  }
}
function handleDeFinish() {
  if (form.value.id != null && form.value.status == 'FINISHED') {
    form.value.status = 'PREPARE';
    form.value.subjectCodes = form.value.subjects.map(item => item.subjectCode).join(",");
    updateCheckplan(form.value).then(response => {
      proxy.$modal.msgSuccess(proxy.tLang('common', '已停用'));
      open.value = false;
      getList();
    }, err => {
      form.value.status = 'FINISHED';
    });
  }
}
/** 删除按钮操作 */
function handleDelete(row) {
  const ids1 = row.id || ids.value;

  proxy.$modal.confirm(proxy.tLang('tip', '确定删除选中记录？') + ids1 ).then(function () {
    return delCheckplan(ids1);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess(proxy.tLang('common', '删除成功'));
  }).catch(() => { })
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download('dv/checkplan/export', {
    ...queryParams
  }, `checkplan_${new Date().getTime()}.xlsx`)
}
//自动生成编码
function handleAutoGenChange(autoGenFlag) {
  if (autoGenFlag) {
    genCode('CHECKPLAN_CODE').then(response => {
      form.value.planCode = response;
    });
  } else {
    form.value.planCode = null;
  }
}
onMounted(() => {
  getList();
  getDeviceList();
  selectListInit();
})
</script>

<style lang="scss" scoped></style>
