<template>
  <div class="mainContentBox">
    <avue-crud
      ref="crudRef"
      v-model:search="search"
      v-model="form"
      :data="data"
      :option="option"
      v-model:page="page"
      @row-save="createRow"
      @row-update="updateRow"
      @row-del="deleteRow"
      @search-change="searchChange"
      @search-reset="resetChange"
      @size-change="dataList"
      @current-change="dataList"
      @selection-change="selectionChange"
    >
      <!--      <template #menu-left="{ size }">
        <el-button
          :disabled="toDeleteIds.length < 1"
          type="danger"
          icon="el-icon-delete"
          :size="size"
          @click="multipleDelete"
          >删除</el-button
        >
      </template>-->
      <template #menu="{ size, row, index }">
        <el-button
          @click="maintenance(row)"
          icon="el-icon-setting"
          text
          type="primary"
          :size="size"
          v-if="radio1 == '1'"
          >计量</el-button
        >
        <PDFView
          :need-to-show-pdf="true"
          content-type="button"
          :is-link="true"
          :pdf-source="filePath + row.pdfPath"
          v-if="radio1 == '2' && row.pdfPath != ''"
        />
        <el-button
          @click="maintenance1(row)"
          icon="el-icon-setting"
          text
          type="primary"
          :size="size"
          v-if="radio1 == '2'"
          >更新附件</el-button
        >
      </template>
      <template #menu-left="{}">
        <el-radio-group
          v-model="radio1"
          size="large"
          @change="searchChangeState"
        >
          <el-radio-button label="待计量" value="1" />
          <el-radio-button label="已计量" value="2" />
        </el-radio-group>
      </template>
      <template #menu-right="{}">
        <el-button
          v-if="radio1 == '1'"
          class="ml-3"
          @click="exportData('/api/v1/device/export')"
        >
          <template #icon> <i-ep-download /> </template>导出
        </el-button>
        <el-button
          v-if="radio1 == '2'"
          class="ml-3"
          @click="exportData('/api/v1/device/metering/exportMetering')"
        >
          <template #icon> <i-ep-download /> </template>导出
        </el-button>
      </template>
    </avue-crud>
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="850px"
      @close="dialog.visible = false"
    >
      <device-page @device-info="deviceInfo" />
    </el-dialog>

    <el-dialog
      v-model="dialog1.visible"
      :title="dialog1.title"
      width="750px"
      height="80%"
      @close="dialog1.visible = false"
    >
      <el-timeline style="max-width: 500px; margin-left: 100px">
        <!--        <el-timeline-item center color="#0bbd87" type="success" placement="top">
          <el-card>
            <h4>维护计划</h4>
            <p>设备编号： {{maintenanceInfo.deviceNo}}</p>
            <p>设备名称：{{maintenanceInfo.deviceName}}</p>
            <p>维护内容：{{maintenanceInfo.remark}}</p>
            <p>计划时间：{{maintenanceInfo.nextTime}}</p>
          </el-card>
        </el-timeline-item>-->
        <!--        <el-timeline-item center placement="top" :type="maintenanceInfo.state === 0 ? 'primary' : 'success'">-->
        <el-card>
          <h4>设备计量</h4>
          <el-form
            ref="maintenanceInfoForm"
            :model="maintenanceInfo"
            label-width="auto"
            style="max-width: 400px"
            :rules="rules"
          >
            <el-form-item label="检测单位" prop="meteringUnit">
              <el-select
                v-model="maintenanceInfo.meteringUnit"
                placeholder="检测单位"
                size="large"
                style="width: 240px"
              >
                <el-option
                  v-for="item in unitList"
                  :key="item.dictLabel"
                  :label="item.dictLabel"
                  :value="item.dictLabel"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="ABC类" prop="meteringType">
              <el-select
                v-model="maintenanceInfo.meteringType"
                placeholder="ABC类"
                size="large"
                style="width: 240px"
              >
                <el-option
                  v-for="item in abc"
                  :key="item.dictLabel"
                  :label="item.dictLabel"
                  :value="item.dictLabel"
                />
              </el-select>
            </el-form-item>

            <!--        <single-upload v-model="form.drawingPath" :generatePdf="true"/>-->

            <el-form-item label="计量周期" prop="cycle">
              <el-input
                v-model="maintenanceInfo.cycle"
                placeholder="计量周期"
                size="large"
                width="240px"
              />
            </el-form-item>

            <el-form-item label="计量结果">
              <el-radio-group v-model="maintenanceInfo.result" class="ml-4">
                <el-radio :value="0">合格</el-radio>
                <el-radio :value="1">不合格</el-radio>
              </el-radio-group>
            </el-form-item>
            <!--              <el-form-item v-if="maintenanceInfo.result === 1" label="报故内容">
                <el-input v-model="maintenanceInfo.maintenanceContent" />
              </el-form-item>-->
            <el-form-item label="附件上传">
              <el-radio-group v-model="maintenanceInfo.upload" class="ml-4">
                <FilesUpload
                  v-model:src="fileUrl"
                  v-model:pdf-list="pdfUrlList"
                  v-model:file-name-list="fileNameList"
                  :generate-pdf="true"
                  @finished="testFiles"
                />
              </el-radio-group>
            </el-form-item>
            <el-form-item label="计量日期" prop="maintenanceTime">
              <el-date-picker
                v-model="maintenanceInfo.maintenanceTime"
                type="date"
                style="width: 240px"
                placeholder="请选择时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />

              <!--                <el-input v-model="maintenanceInfo.nextTime" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD"/>-->
            </el-form-item>
            <el-form-item label="下次计量日期" prop="nextTime">
              <el-date-picker
                v-model="maintenanceInfo.nextTime"
                type="date"
                style="width: 240px"
                :disabled-date="disabledDate"
                placeholder="请选择时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />

              <!--                <el-input v-model="maintenanceInfo.nextTime" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD"/>-->
            </el-form-item>
            <!--              <el-form-item v-if="maintenanceInfo.result === 0" label="下次维护内容">
                <el-input v-model="maintenanceInfo.maintenanceContent" />
              </el-form-item>-->
            <el-form-item style="margin-left: 45%">
              <el-button type="primary" @click="maintenanceSubmit"
                >保存</el-button
              >
            </el-form-item>
          </el-form>
        </el-card>
        <!--        </el-timeline-item>-->
      </el-timeline>
    </el-dialog>
    <el-dialog
      v-model="dialog3.visible"
      :title="dialog3.title"
      width="750px"
      height="80%"
      @close="dialog1.visible = false"
    >
      <el-timeline style="max-width: 500px; margin-left: 100px">
        <!--        <el-timeline-item center color="#0bbd87" type="success" placement="top">
                  <el-card>
                    <h4>维护计划</h4>
                    <p>设备编号： {{maintenanceInfo.deviceNo}}</p>
                    <p>设备名称：{{maintenanceInfo.deviceName}}</p>
                    <p>维护内容：{{maintenanceInfo.remark}}</p>
                    <p>计划时间：{{maintenanceInfo.nextTime}}</p>
                  </el-card>
                </el-timeline-item>-->
        <!--        <el-timeline-item center placement="top" :type="maintenanceInfo.state === 0 ? 'primary' : 'success'">-->
        <el-card>
          <h4>更改附件</h4>
          <el-form
            ref="maintenanceInfoForm1"
            :model="maintenanceInfo1"
            label-width="auto"
            style="max-width: 400px"
            :rules="rules"
          >
            <!--        <single-upload v-model="form.drawingPath" :generatePdf="true"/>-->

            <!--              <el-form-item v-if="maintenanceInfo.result === 1" label="报故内容">
                            <el-input v-model="maintenanceInfo.maintenanceContent" />
                          </el-form-item>-->
            <el-form-item label="附件上传">
              <el-radio-group v-model="maintenanceInfo1.upload" class="ml-4">
                <FilesUpload
                  v-model:src="fileUrl1"
                  v-model:pdf-list="pdfUrlList1"
                  v-model:file-name-list="fileNameList1"
                  :generate-pdf="true"
                  @finished="testFiles1"
                />
              </el-radio-group>
            </el-form-item>

            <!--              <el-form-item v-if="maintenanceInfo.result === 0" label="下次维护内容">
                            <el-input v-model="maintenanceInfo.maintenanceContent" />
                          </el-form-item>-->
            <el-form-item style="margin-left: 45%">
              <el-button type="primary" @click="maintenanceSubmit1"
                >保存</el-button
              >
            </el-form-item>
          </el-form>
        </el-card>
        <!--        </el-timeline-item>-->
      </el-timeline>
    </el-dialog>
    <el-dialog
      v-model="dialog2.visible"
      :title="dialog2.title"
      width="60%"
      height="80%"
      @close="dialog2.visible = false"
    >
      <record-page :maintenanceId="maintenanceInfo.id" />
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, getCurrentInstance } from "vue";
import { useCrud } from "@/hooks/userCrud";
import ButtonPermKeys from "@/common/configs/buttonPermission";
import { getUserList } from "@/api/system/user";
import { queryDictDataByType } from "@/api/system/dict";
import {
  maintenanceUpdate,
  meteringUpdate,
  meteringUpdateFile,
} from "@/api/device/index";
import { useCommonStoreHook } from "@/store";
import dictDataUtil from "@/common/configs/dictDataUtil";
import RecordPage from "./components/metering-record.vue";
import PDFView from "@/components/PDFView/index.vue";
const { isShowTable, tableType } = toRefs(useCommonStoreHook());
const pdfUrlList = ref([]);
const fileUrl = ref();
const fileNameList = ref([]);
const pdfUrlList1 = ref([]);
const fileUrl1 = ref();
const fileNameList1 = ref([]);
const typeList = ref([]);
const filePath = import.meta.env.VITE_APP_UPLOAD_URL;
const test = () => {
  isShowTable.value = true;
  tableType.value = tableType.value == 1 ? 2 : 1;
};
const searchChangeState = () => {
  search.value.needMetering = radio1.value;
  if (radio1.value == "1") {
    crudRef.value.option.column = column1.value;
  }
  if (radio1.value == "2") {
    crudRef.value.option.column = column2.value;
    //crudRef.value.option=option1;
  }
  dataList();
};

const radio1 = ref("1");
const disabledDate = (time) => {
  return time.getTime() < Date.now(); // 8.64e7 毫秒数代表一天
};
const dialog = reactive({
  title: "设备选择",
  visible: false,
});
const dialog1 = reactive({
  title: "设备计量",
  visible: false,
});
const dialog2 = reactive({
  title: "设备计量记录",
  visible: false,
});
const dialog3 = reactive({
  title: "更新附件",
  visible: false,
});
const userList = ref([]);
const unitList = ref([]);
const abc = ref([]);
// 传入一个url，后面不带/
const { form, data, option, search, page, toDeleteIds, Methords, Utils } =
  useCrud({
    src: "/api/v1/device/metering",
  });
const { dataList, createRow, updateRow, deleteRow, searchChange, resetChange } =
  Methords; //增删改查
const { selectionChange, multipleDelete } = Methords; //选中和批量删除事件
const { checkBtnPerm, downloadTemplate, exportData } = Utils; //按钮权限等工具
const crudRef = ref(null); //crudRef.value 获取avue-crud对象
const deviceInfo = (value) => {
  form.value.deviceNo = value.deviceNo;
  dialog.visible = false;
};
const maintenanceInfo = ref(null);
const maintenanceInfo1 = ref({});
const maintenance = (row) => {
  maintenanceInfo.value = row;
  maintenanceInfo.value.deviceId = row.id;
  maintenanceInfo.value.result = 0;
  dialog1.visible = true;
};
const maintenance1 = (row) => {
  maintenanceInfo1.value.id = row.id;
  dialog3.visible = true;
};
const testFiles = () => {
  maintenanceInfo.value.pdfPath = pdfUrlList.value[0];
  maintenanceInfo.value.filePath = fileUrl.value;
  maintenanceInfo.value.fileName = fileNameList.value[0];
};
const testFiles1 = () => {
  maintenanceInfo1.value.pdfPath = pdfUrlList1.value[0];
  maintenanceInfo1.value.filePath = fileUrl1.value;
  maintenanceInfo1.value.fileName = fileNameList1.value[0];
  maintenanceInfo1.value.upload = fileUrl1.value;
};
const maintenanceList = (row) => {
  maintenanceInfo.value = row;
  dialog2.visible = true;
};
const queryUserList = () => {
  getUserList({}).then((data) => {
    userList.value = data.data;
  });
};

const queryUnitList = () => {
  queryDictDataByType("metering_unit").then((data) => {
    unitList.value = data.data;
  });
};
const queryAbc = () => {
  queryDictDataByType("ABC").then((data) => {
    abc.value = data.data;
  });
};
const maintenanceInfoForm = ref("maintenanceInfoForm");
const maintenanceInfoForm1 = ref("maintenanceInfoForm1");
const maintenanceSubmit = () => {
  //alert(JSON.stringify(maintenanceInfo.value))
  maintenanceInfoForm.value.validate((isValid, invalidFields) => {
    if (isValid) {
      meteringUpdate(maintenanceInfo.value).then((data) => {
        ElMessage({
          message: data.msg,
          type: "success",
        });
        maintenanceInfo.value = {};
        pdfUrlList.value = [];
        fileUrl.value = {};
        fileNameList.value = [];
        dialog1.visible = false;
        dataList();
      });
    }
  });
};
const maintenanceSubmit1 = () => {
  //alert(JSON.stringify(maintenanceInfo.value))
  maintenanceInfoForm1.value.validate((isValid, invalidFields) => {
    if (isValid) {
      meteringUpdateFile(maintenanceInfo1.value).then((data) => {
        ElMessage({
          message: data.msg,
          type: "success",
        });
        maintenanceInfo1.value = {};
        dialog3.visible = false;
        pdfUrlList1.value = [];
        fileUrl1.value = {};
        fileNameList1.value = [];
        search.value.needMetering = "2";
        dataList();
      });
    }
  });
};
const rules = reactive({
  meteringUnit: [
    // required是否必填,message不符合此规则时的提示信息,
    // trigger触发此条规则校验的时机，有两个值, blur 或 change,默认就是blur和change都会进行校验
    // min此字段的最小长度，max此字段的最大长度
    // pattern 正则表达式
    { required: true, message: "计量人员不能为空", trigger: "blur" },
  ],
  nextTime: [
    { required: true, message: "下次计量日期不能为空", trigger: "blur" },
  ],
  maintenanceTime: [
    { required: true, message: "计量日期不能为空", trigger: "blur" },
  ],
  meteringType: [{ required: true, message: "ABC类不能为空", trigger: "blur" }],
  cycle: [{ required: true, message: "计量周期不能为空", trigger: "blur" }],
});
// 设置表格列或者其他自定义的option
option.value = Object.assign(option.value, {
  delBtn: false,
  selection: false,
  labelWidth: 150,
  addBtn: false,
  editBtn: false,
  viewBtn: false,
  column: [
    {
      label: "本所编码",
      prop: "deviceNo",
      search: true,
      overHidden: true,
    },
    {
      label: "设备名称",
      prop: "deviceName",
      search: true,
      overHidden: true,
    },
    {
      label: "设备型号",
      prop: "specifications",
      overHidden: true,
    },
    {
      label: "出厂编号",
      prop: "serialNumber",
      search: true,
      overHidden: true,
    },

    {
      label: "使用单位",
      prop: "deptId",
      width: 100,
      overHidden: true,
      type: "tree",
      dicUrl: dictDataUtil.dept_tree_url,
      props: {
        label: "deptName",
        value: "id",
      },
    },
    {
      label: "存放位置",
      prop: "devicePosition",
      width: 160,
      overHidden: true,
    },

    {
      label: "计量日期",
      prop: "meteringSearch",
      width: 160,
      type: "daterange",
      searchRange: true,
      hide: true,
      startPlaceholder: "开始范围",
      endPlaceholder: "结束范围",
      format: "YYYY-MM-DD",
      valueFormat: "YYYY-MM-DD",
      overHidden: true,
      search: true,
    },
    {
      label: "设备类型",
      prop: "deviceType",
      type: "select",
      width: 130,
      hide: true,
      overHidden: true,
      dicUrl: dictDataUtil.request_url + dictDataUtil.TYPE_CODE.device_type,
      props: {
        label: "dictLabel",
        value: "dictValue",
      },
    },

    {
      label: "责任人",
      prop: "head",
      overHidden: true,
    },
    {
      label: "计量有效期",
      prop: "meteringDate",
      type: "date",
      format: "YYYY-MM-DD",
      valueFormat: "YYYY-MM-DD",
      overHidden: true,
    },
  ],
});
const column1 = ref([
  {
    label: "本所编码",
    prop: "deviceNo",
    search: true,
    overHidden: true,
  },
  {
    label: "设备名称",
    prop: "deviceName",
    search: true,
    overHidden: true,
  },
  {
    label: "设备型号",
    prop: "specifications",
    overHidden: true,
  },
  {
    label: "出厂编号",
    prop: "serialNumber",
    overHidden: true,
  },

  {
    label: "使用单位",
    prop: "deptId",
    overHidden: true,
    type: "tree",
    dicUrl: dictDataUtil.dept_tree_url,
    props: {
      label: "deptName",
      value: "id",
    },
  },
  {
    label: "存放位置",
    prop: "devicePosition",
    width: 160,
    overHidden: true,
  },

  {
    label: "计量日期",
    prop: "meteringSearch",
    width: 160,
    type: "daterange",
    searchRange: true,
    hide: true,
    startPlaceholder: "开始范围",
    endPlaceholder: "结束范围",
    format: "YYYY-MM-DD",
    valueFormat: "YYYY-MM-DD",
    overHidden: true,
    search: true,
  },
  {
    label: "设备类型",
    prop: "deviceType",
    type: "select",
    hide: true,
    overHidden: true,
    dicUrl: dictDataUtil.request_url + dictDataUtil.TYPE_CODE.device_type,
    props: {
      label: "dictLabel",
      value: "dictValue",
    },
  },

  {
    label: "责任人",
    prop: "head",
    overHidden: true,
  },
  {
    label: "计量有效期",
    prop: "meteringDate",
    type: "date",
    format: "YYYY-MM-DD",
    valueFormat: "YYYY-MM-DD",
    overHidden: true,
  },
]);
const column2 = ref([
  {
    label: "本所编码",
    prop: "deviceNo",
    search: true,
    width: 160,
    overHidden: true,
  },
  {
    label: "设备名称",
    prop: "deviceName",
    search: true,
    width: 160,
    overHidden: true,
  },
  {
    label: "设备型号",
    prop: "specifications",
    width: 160,
    overHidden: true,
  },
  {
    label: "出厂编号",
    prop: "serialNumber",
    width: 160,
    overHidden: true,
  },
  {
    label: "检验单位",
    prop: "meteringUnit",
    width: 160,
    overHidden: true,
  },
  {
    label: "使用单位",
    prop: "deptId",
    width: 100,
    overHidden: true,
    type: "tree",
    dicUrl: dictDataUtil.dept_tree_url,
    props: {
      label: "deptName",
      value: "id",
    },
  },
  {
    label: "存放位置",
    prop: "devicePosition",
    width: 160,
    overHidden: true,
  },
  {
    label: "ABC类",
    prop: "meteringType",
    width: 160,
    overHidden: true,
  },

  {
    label: "计量日期",
    prop: "meteringSearch",
    width: 160,
    type: "daterange",
    hide: true,
    searchRange: true,
    startPlaceholder: "开始范围",
    endPlaceholder: "结束范围",
    format: "YYYY-MM-DD",
    valueFormat: "YYYY-MM-DD",
    overHidden: true,
    search: true,
  },
  {
    label: "计量日期",
    prop: "maintenanceTime",
    width: 160,
    searchRange: true,
    valueFormat: "YYYY-MM-DD",
    overHidden: true,
  },
  {
    label: "计量周期",
    prop: "cycle",
    width: 160,
    overHidden: true,
  },
  {
    label: "结果",
    prop: "result",
    dicData: [
      {
        label: "合格",
        value: 0,
      },
      {
        label: "不合格",
        value: 1,
      },
    ],
  },
  {
    label: "设备类型",
    prop: "deviceType",
    type: "select",
    width: 130,
    hide: true,
    overHidden: true,
    dicUrl: dictDataUtil.request_url + dictDataUtil.TYPE_CODE.device_type,
    props: {
      label: "dictLabel",
      value: "dictValue",
    },
  },
  {
    label: "责任人",
    prop: "head",
    width: 160,
    overHidden: true,
  },
  {
    label: "下次计量时间",
    prop: "nextTime",
    type: "date",
    width: 160,
    format: "YYYY-MM-DD",
    valueFormat: "YYYY-MM-DD",
    overHidden: true,
  },
  {
    label: "附件",
    prop: "fileName",
    width: 160,
    overHidden: true,
  },
  {
    label: "附件下载",
    prop: "filePath",
    width: 120,
    html: true,
    formatter: (val) => {
      if (val.filePath != "") {
        return (
          '<a class="el-tag el-tag--info el-tag--light" href="' +
          filePath +
          val.filePath +
          '" >文件下载</a>'
        );
      } else {
        return val.filePath;
      }
    },
  },
]);
// 设置表格列或者其他自定义的option

onMounted(() => {
  search.value.needMetering = "1";
  maintenanceInfo.value.result = "0";
  dataList();
  //queryUserList()
  queryUnitList();
  queryAbc();
});
</script>
<style>
.demo-tabs > .el-tabs__content {
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
</style>
