<template>
  <div class="content-box">
    <div class="left">
      <!-- <el-icon :size="23" class="camera"><VideoCameraFilled /></el-icon> -->
      <span class="cameratxt" @click="getList(1)" :class="themeIndex == 1 ? 'is_active' : ''">耗材管理</span>
      <span class="cameratxt" @click="getList(2)" :class="themeIndex == 2 ? 'is_active' : ''">耗材记录</span>
    </div>
    <div v-if="themeIndex == 1">
      <div class="middle">
        <div class="filter">
          <div class="condition">
            <span>关键字 : </span>
            <el-input clearable v-model="searchInput.name" @clear="searchBtn" class="w-50 m-2" placeholder="请输入名称"
              style="width: 150px" />
          </div>
          <div class="condition">
            <span>创建时间 : </span>
            <el-date-picker v-model="searchInput.createTime" type="daterange" range-separator="-" start-placeholder="起始时间"
              end-placeholder="结束时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD" :prefix-icon="Calendar"
              placeholder="请选择日期" />
          </div>
          <div class="condition">
            <span>校区 : </span>
            <el-select v-model="searchInput.schoolId" class="m-2" placeholder="请选择校区" @change="selSchool">
              <el-option label="全部校区" :value="0" />
              <el-option label="黄家湖校区" :value="1" />
              <el-option label="墨轩湖校区" :value="2" />
            </el-select>
          </div>
          <el-button style="margin-left: 20px" color="rgba(111, 182, 184, 1)" type="primary" class="search"
            @click="searchBtn"><el-icon>
              <Search />
            </el-icon> <span>查询</span></el-button>
        </div>
        <!-- 按钮列表 -->
        <div class="gongneng">
          <el-button type="primary" color="rgba(111, 182, 184, 1)" @click="addlist"><img src="@/assets/add.png"
              style="width: 14px; height: 14px; margin-right: 4px" alt="" /><span>添加耗材</span></el-button>
          <el-button color="rgba(111, 182, 184, 1)" class="import" type="primary" @click="importFile"><img
              src="@/assets/toLead.png" style="width: 24px; height: 22px" alt="" />
            <span>导入耗材</span></el-button>
          <el-button color="rgba(111, 182, 184, 1)" class="import" type="primary" @click="importExcel1"><img
              src="@/assets/import.png" style="width: 14px; height: 14px; margin-right: 4px" alt="" />
            <span>导出耗材</span></el-button>
        </div>
      </div>
      <div class="footer" :key="keyIndex">
        <el-table :row-class-name="tableRowClassName" :data="tableData.list" style="width: 100%" :header-cell-style="{
          background: 'rgba(240, 243, 247, 1)',
          height: '50px',
          border: 0,
        }">
          <!-- <el-table-column align="center" type="selection" width="80" /> -->
          <el-table-column width="80" align="center" type="index" prop="1" label="序号" />
          <el-table-column width="220" align="center" prop="name" label="品名" />
          <el-table-column align="center" prop="price" label="单价(元)" />
          <el-table-column width="150" align="center " label="校区">
            <template #default="{ row }">
              <span>{{ row.schoolId == 1 ? "黄家湖校区" : "墨轩湖校区" }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column width="250" align="center" prop="content" show-overflow-tooltip label="耗材内容" />
          <el-table-column align="center" show-overflow-tooltip label="关联物品种类" width="250">
            <template #default="{ row }">
              <span v-if="row.articleNames">{{
                row.articleNames.join(",")
              }}</span>
            </template>
          </el-table-column> -->
          <el-table-column align="center" prop="userName" label="录入人" />
          <el-table-column align="center" prop="updateTime" label="创建时间" />
          <el-table-column align="center" label="操作" width="220">
            <template #default="scope">
              <div class="edit">
                <div class="look" @click="edit(scope.row)">编辑</div>
                <el-popconfirm width="220" confirm-button-text="确认" cancel-button-text="取消" :icon="InfoFilled"
                  icon-color="#f89626" :title="`是否删除 ${scope.row.name} 物品?`" @confirm="del(scope.row)"
                  @cancel="cancelEvent">
                  <template #reference>
                    <div class="look">删除</div>
                  </template>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 添加耗材弹窗 -->
        <el-dialog class="addStaff" v-model="addDialogVisible" :close-on-click-modal="false"
          :close-on-press-escape="false" :title="dialongTitle" align-center width="609" :before-close="handleVideoClose">
          <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
            :size="formSize" label-position="left" status-icon>
            <el-form-item label="耗材名称 :" prop="name">
              <el-input clearable v-model="ruleForm.name" placeholder="请输入耗材名称" />
            </el-form-item>
            <el-form-item label="校区 :" prop="schoolId">
              <el-select v-model="ruleForm.schoolId" class="m-2" placeholder="请选择校区" @change="changeSchool">
                <el-option label="黄家湖校区" :value="1" />
                <el-option label="墨轩湖校区" :value="2" />
              </el-select>
            </el-form-item>
            <el-form-item label="单价 :" prop="price">
              <el-input clearable v-model="ruleForm.price" placeholder="请输入单价" />
            </el-form-item>
            <el-form-item label="关联物品种类 :" prop="articleIds" class="checkbox">
              <el-tree :data="articleIdsList" :props="{ label: 'name', children: 'children', value: 'id' }" node-key="id"
                show-checkbox ref="articleIdsRef" @check-change="handleArticleIds" />
              <!-- <el-checkbox
                v-model="checkAll"
                :indeterminate="isIndeterminate"
                @change="handleCheckAllChange"
                >全选</el-checkbox
              >
              <el-checkbox-group
                v-model="checkedCities"
                @change="handleCheckedCitiesChange"
              >
                <el-checkbox
                  v-for="item in articleIdsList"
                  :label="item.name"
                  >{{ item.name }}</el-checkbox
                >
              </el-checkbox-group> -->
            </el-form-item>
            <el-form-item label="报修内容 :">
              <el-input v-model="ruleForm.content" :rows="3" type="textarea" show-word-limit :autofocus="true"
                placeholder="请输入报修内容" />
            </el-form-item>
            <!-- <el-form-item
              label="关联物品种类 :"
              prop="volume"
              class="checkbox"
              style="
                padding-bottom: 40px;
                border-bottom: 1px solid rgba(230, 230, 230, 1);
              "
            >
              <el-checkbox
                v-model="checkAll"
                :indeterminate="isIndeterminate"
                @change="handleCheckAllChange"
                >全选</el-checkbox
              >
              <el-checkbox-group
                v-model="checkedCities"
                @change="handleCheckedCitiesChange"
              >
                <el-checkbox v-for="city in cities" :key="city" :label="city">{{
                  city
                }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item> -->

            <el-form-item class="options">
              <el-button color="rgba(111, 182, 184, 1)" class="queding" type="primary" @click="submitAdd(ruleFormRef)">
                确定
              </el-button>
              <el-button class="congzhi" @click="cancelAdd(ruleFormRef)">取消</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
        <!-- 导入弹窗 -->
        <el-dialog class="importXlsx" v-model="importXlsx" :close-on-click-modal="false" :close-on-press-escape="false"
          title="导入文件" align-center width="409" :before-close="closeXlsx">
          <div class="el_btn">
            <el-button type="primary" color="rgb(243, 144, 122)" @click="importTemp">
              <span style="color: #fff">下载文件模板</span></el-button>
            <el-upload class="avatar-uploader" action="" ref="upload" :on-preview="handlePreview"
              :on-remove="handleRemove" :on-change="handleChange" :http-request="handleUpload"
              :before-upload="beforeAvatarUpload" :auto-upload="false" :limit="1" :on-exceed="handleExceed">
              <template #trigger>
                <el-button type="primary" color="rgba(111, 182, 184, 1)" @click="updateImg">
                  <img src="@/assets/toLead.png" style="width: 24px; height: 22px" alt="" />
                  <span style="color: #fff">导入文件</span></el-button>
              </template>
              <!-- <template #tip>
              <div class="el-upload__tip">
                （注：图片大小不超过10M，建议按3:2比例）
              </div>
            </template> -->
            </el-upload>
          </div>
          <div class="options">
            <el-button color="rgba(111, 182, 184, 1)" class="queding" type="primary" @click="importSuc()">
              确定
            </el-button>
            <el-button class="congzhi" @click="closeXlsx()">取消</el-button>
          </div>
        </el-dialog>
      </div>

      <!-- 分页组件 -->
      <div class="pageSize">
        <span></span>
        <el-pagination background :current-page="currentPage" :page-size="pageSize"
          layout="total, prev, pager, next, jumper, slot" :total="total" @update:current-page="handleCurrentChange" />
      </div>
    </div>
    <div v-else-if="themeIndex == 2">
      <div class="middle">
        <div class="filter">
          <div class="condition">
            <span>关键字 : </span>
            <el-input clearable v-model="searchInput2.name" @clear="searchBtn" class="w-50 m-2" placeholder="请输入工单或耗材名称"
              style="width: 150px" />
          </div>
          <div class="condition">
            <span>维修时间 : </span>
            <el-date-picker v-model="searchInput2.createTime" type="daterange" range-separator="-"
              start-placeholder="起始时间" end-placeholder="结束时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
              :prefix-icon="Calendar" placeholder="请选择日期" />
          </div>
          <div class="condition">
            <span>校区 : </span>
            <el-select v-model="searchInput2.schoolId" class="m-2" placeholder="请选择校区" @change="selSchool">
              <el-option label="全部校区" :value="0" />
              <el-option label="黄家湖校区" :value="1" />
              <el-option label="墨轩湖校区" :value="2" />
            </el-select>
          </div>
          <el-button style="margin-left: 20px" color="rgba(111, 182, 184, 1)" type="primary" class="search"
            @click="searchBtn"><el-icon>
              <Search />
            </el-icon> <span>查询</span></el-button>
        </div>
        <!-- 按钮列表 -->
        <div class="gongneng">
          <el-button color="rgba(111, 182, 184, 1)" class="import" type="primary" @click="importExcel2"><img
              src="@/assets/import.png" style="width: 14px; height: 14px; margin-right: 4px" alt="" />
            <span>导出耗材记录</span></el-button>
        </div>
      </div>
      <div class="footer" :key="keyIndex">
        <el-table :row-class-name="tableRowClassName" :data="tableData2.list" @selection-change="handleSelectionChange2"
          style="width: 100%" :header-cell-style="{
            background: 'rgba(240, 243, 247, 1)',
            height: '50px',
            border: 0,
          }">
          <!-- <el-table-column align="center" type="selection" width="80" /> -->
          <el-table-column width="80" align="center " type="index" label="序号" />
          <el-table-column align="center" prop="schoolName" label="校区" />
          <el-table-column align="center" prop="areaName" label="区域" width="210" />
          <el-table-column align="center" prop="consumeName" width="150" show-overflow-tooltip label="品名" />
          <el-table-column align="center" prop="price" label="单价(元)" width="90" />
          <el-table-column align="center" prop="number" label="数量" width="80" />
          <el-table-column align="center" prop="totalPrice" label="金额(元)" width="90" />
          <!-- <el-table-column align="center" prop="articleName" label="关联故障种类" /> -->
          <el-table-column align="center" prop="statu" label="状态" width="90" />
          <el-table-column align="center" prop="changeUser" label="改价人" />
          <el-table-column align="center" prop="recordNo" label="工单" width="150" />
          <el-table-column align="center" prop="reportTime" label="报修时间" />
          <el-table-column align="center" prop="updateTime" label="维修时间" />
        </el-table>
      </div>

      <!-- 分页组件 -->
      <div class="pageSize">
        <span>合计: {{pieceNum}}件&nbsp;&nbsp;&nbsp;{{pieceMoney}}元</span>
        <el-pagination background :current-page="currentPage2" :page-size="pageSize2"
          layout="total, prev, pager, next, jumper, slot" :total="total2" @update:current-page="handleCurrentChange2" />
      </div>
    </div>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  nextTick,
  watch,
  onBeforeMount,
  onUnmounted,
} from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Calendar } from "@element-plus/icons-vue";
import vidiconsApi from "@/api/vidicons.js";
import { dayjs } from "element-plus";
import lodash from "lodash";
import axios from "axios";
import { useStore } from "vuex";
const store = useStore();
const api = ref("");
const router = useRouter();
// 表格数据
const tableData = reactive({ list: [] });
const tableData2 = reactive({ list: [] });

const themeIndex = ref(2); // 切换 耗材管理 和 耗材记录
const keyIndex = ref(1) // 切换时将key改变使组件重新加载

// 添加耗材 弹窗数据 (------------------------------------)
const dialongTitle = ref("添加耗材"); // 弹窗标题
// const checkAll = ref(false); // 判断物品种类是否全选
// const isIndeterminate = ref(true); // 不确定状态，表示只选择一部分
// const checkedCities = ref(["泥工", "木工"]); // 选中的数据
// const cities = ["水电类", "泥工", "木工", "其他"]; //  种类列表
const articleIdsList = ref(); // 关联物品种类
const articleIdsRef = ref(); // 关联物品种类ref

const searchInput = reactive({
  name: "",
  createTime: "",
  schoolId: ""
}); // 搜索按钮数据
const searchInput2 = reactive({
  name: "",
  createTime: "",
  schoolId: ""
}); // 搜索按钮数据
5;
// 耗材管理页面（---------------------------------------------）
const currentPage = ref(1); // 当前页
const pageSize = ref(10);
const total = ref(); // 当前总数
const selectData = reactive({ list: [] }); // 多选框选择的数据

const upload = ref(); // 导入按钮ref
const fileXlsx = ref(); // 导入的文件file
const importXlsx = ref(false); // 导入弹窗

const addDialogVisible = ref(false); // 控制添加员工弹窗

// 耗材管理表单数据
const formSize = ref("default");
const ruleFormRef = ref();
const ruleForm = reactive({
  name: "",
  articleIds: "",
  price: "",
  content: "",
  schoolId: "",
  id: "",
});
// 表单验证
const rules = reactive({
  // serial: [{ required: true, message: "序列号不能为空", trigger: "blur" }],
  name: [{ required: true, message: "耗材名称", trigger: "blur" }],
  price: [{ required: true, message: "耗材单价", trigger: "blur" }],
  schoolId: [{ required: true, message: "校区不能为空", trigger: "blur" }],
  articleIds: [
    { required: true, message: "关联物品种类不能为空", trigger: "blur" },
  ],
});

// 耗材记录页面（---------------------------------------------）
const currentPage2 = ref(1); // 当前页
const pageSize2 = ref(10);
const total2 = ref(30); // 当前总数
const pieceNum=ref()// 耗材记录件数
const pieceMoney=ref()// 耗材记录金额

watch(
  () => searchInput.createTime,
  (newVal, oldVal) => {
    console.log("监听时间:", newVal);
    if (newVal == null) {
      searchBtn();
    }
  }
);
watch(
  () => searchInput2.createTime,
  (newVal, oldVal) => {
    console.log("监听时间:", newVal);
    if (newVal == null) {
      searchBtn();
    }
  }
);
// 查看耗材管理列表
const getList = async (flag) => {
  keyIndex.value++;
  // 耗材管理(-----------------------------------------------)
  if (flag == 1) {
    themeIndex.value = 1;
    let data = {
      currentPage: currentPage.value,
      pageCount: pageSize.value,
      name: searchInput.name,
    };
    if (searchInput.createTime) {
      data.startTime = searchInput.createTime[0];
      data.endTime = searchInput.createTime[1];
    }

    let res = await axios({
      method: "get",
      url: api.value + "/repairConsume/queryPageRepairConsume",
      headers: {
        token: sessionStorage.getItem("token"),
        user_head: sessionStorage.getItem("userhead"),
      },
      params: data,
    });
    console.log(res, "耗材管理");
    if (res.data.code == 200) {
      tableData.list = res.data.data.list;
      total.value = res.data.data.totalCount;
      // ElMessage({
      //   type: "success",
      //   showClose: true,
      //   message: res.data.message,
      //   center: true,
      // });
    } else {
      ElMessage({
        type: "error",
        showClose: true,
        message: res.data.message,
        center: true,
      });
      if (res.data.code == 570) {
        sessionStorage.removeItem("token")
        router.push({
          path: `/login`,
        });
      }
    }
  } else if (flag == 2) {
    themeIndex.value = 2;
    let data = {
      currentPage: currentPage2.value,
      pageCount: pageSize2.value,
      keyWord: searchInput2.name,
    };
    if (searchInput2.createTime) {
      data.startTime = searchInput2.createTime[0];
      data.endTime = searchInput2.createTime[1];
    }

    let res = await axios({
      method: "get",
      url: api.value + "/repairConsumables/queryRepairConsumablePageList",
      headers: {
        token: sessionStorage.getItem("token"),
        user_head: sessionStorage.getItem("userhead"),
      },
      params: data,
    });
    console.log(res, "耗材记录");
    if (res.data.code == 200) {
      tableData2.list = res.data.data.list;
      total2.value = res.data.data.totalCount;
      pieceNum.value = res.data.data.tcont;
      pieceMoney.value = res.data.data.tprice;
    } else {
      ElMessage({
        type: "error",
        showClose: true,
        message: res.data.message,
        center: true,
      });
    }
  }
};

// 搜索功能
const searchBtn = lodash.debounce(async () => {
  getList(themeIndex.value);
}, 300);

//新增添加耗材 （--------------------------------------）
const addlist = () => {
  dialongTitle.value = "添加耗材";
  ruleForm.schoolId = 1;
  changeSchool(ruleForm.schoolId);
  addDialogVisible.value = true;
  ruleForm.name = "";
  ruleForm.price = "";
  ruleForm.articleIds = [];
  ruleForm.content = "";
  nextTick(() => {
    articleIdsRef.value.setCheckedKeys([]);
  });
};
// // 种类是否全选按钮
// const handleCheckAllChange = (val) => {
//   console.log(val);
//   checkedCities.value = val ? cities : [];
//   isIndeterminate.value = false;
// };
// //单独勾选种类
// const handleCheckedCitiesChange = (value) => {
//   console.log(value);
//   const checkedCount = value.length;
//   checkAll.value = checkedCount === cities.length;
//   isIndeterminate.value = checkedCount > 0 && checkedCount < cities.length;
// };

// 关联报修类型  当复选框被点击的时候触发
const handleArticleIds = (data, checked, indeterminate) => {
  console.log(data, checked, indeterminate);
  // let keys = articleIdsRef.value.getCheckedNodes();
  let keys = articleIdsRef.value.getCheckedKeys();
  // console.log(keys);
  // let arr = [];
  // keys.forEach((item) => {
  //   if (item.parentId != 1) {
  //     arr.push(item.id);
  //   }
  // });
  ruleForm.articleIds = keys;
};

// 改变校区  关联楼栋和关联报修类型也改变(---------------)
const changeSchool = async (val) => {
  if (val == 1) {
    ruleForm.schoolId = 1;
  } else {
    ruleForm.schoolId = 2;
  }
  //  报修（故障类型）类型关联 (接口-------)
  let data = {
    schoolId: val,
  };
  let resss = await axios({
    method: "get",
    url: api.value + "/repairArticleType/queryRepairArticleType",
    headers: {
      token: sessionStorage.getItem("token"),
      user_head: sessionStorage.getItem("userhead"),
    },
    params: data,
  });
  console.log(resss, "报修（故障类型）类型关联数据");
  articleIdsList.value = resss.data.data;
};

//编辑按钮  （-------------------------------------------）
const edit = (row) => {
  dialongTitle.value = "编辑耗材";
  addDialogVisible.value = true;
  changeSchool(row.schoolId);
  ruleForm.name = row.name;
  ruleForm.price = row.price;
  ruleForm.articleIds = row.articleIds;
  ruleForm.content = row.content;
  ruleForm.schoolId = row.schoolId;
  nextTick(() => {
    articleIdsRef.value.setCheckedKeys(row.articleIds);
  });
  ruleForm.id = row.id;
};
// 取消 编辑/添加耗材
const cancelAdd = () => {
  addDialogVisible.value = false;
  ruleFormRef.value.resetFields();
};
// 确认 编辑/添加耗材
const submitAdd = async (formEl) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (dialongTitle.value == "添加耗材") {
        // 添加耗材接口（++++++++）
        let data = {
          name: ruleForm.name,
          price: ruleForm.price,
          articleIds: ruleForm.articleIds,
          content: ruleForm.content,
          schoolId: ruleForm.schoolId,
        };

        let res = await axios({
          method: "post",
          url: api.value + "/repairConsume/insertRepairConsume",
          headers: {
            token: sessionStorage.getItem("token"),
            user_head: sessionStorage.getItem("userhead"),
          },
          data: data,
        });
        console.log(res, "添加耗材");
        if (res.data.code == 200) {
          getList(themeIndex.value);
          ElMessage({
            type: "success",
            showClose: true,
            message: res.data.message,
            center: true,
          });
          addDialogVisible.value = false;
          ruleFormRef.value.resetFields();
        } else {
          ElMessage({
            type: "error",
            showClose: true,
            message: res.data.message,
            center: true,
          });
        }
      } else {
        // 编辑耗材接口（++++++++）
        let data = {
          name: ruleForm.name,
          price: ruleForm.price,
          articleIds: ruleForm.articleIds,
          content: ruleForm.content,
          schoolId: ruleForm.schoolId,
          id: ruleForm.id,
        };
        let res = await axios({
          method: "post",
          url: api.value + "/repairConsume/updateRepairConsumeById",
          headers: {
            user_head: sessionStorage.getItem("userhead"),
            token: sessionStorage.getItem("token"),
          },
          data: data,
        });
        // console.log(res, "修改账号");
        if (res.data.code == 200) {
          getList(themeIndex.value);
          ElMessage({
            type: "success",
            showClose: true,
            message: res.data.message,
            center: true,
          });
          addDialogVisible.value = false;
          ruleFormRef.value.resetFields();
        } else {
          ElMessage({
            type: "error",
            showClose: true,
            message: res.data.message,
            center: true,
          });
        }
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 耗材管理删除按钮
const del = async (row) => {
  let data = {
    id: row.id,
  };
  let res = await axios({
    method: "get",
    url: api.value + "/repairConsume/deleteRepairConsumeById",
    headers: {
      token: sessionStorage.getItem("token"),
      user_head: sessionStorage.getItem("userhead"),
    },
    params: data,
  });
  if (res.data.code == 200) {
    if (tableData.list.length == 1 && currentPage.value != 1) {
      currentPage.value = currentPage.value - 1;
    }
    getList(themeIndex.value);
    ElMessage({
      type: "success",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  }
};
// 取消删除
const cancelEvent = () => {
  ElMessage({
    type: "info",
    showClose: true,
    message: "取消删除",
    center: true,
  });
};
//导出功能
const importExcel1 = async () => {
  let datas;
  if (searchInput.createTime) {
    datas = {
      name: searchInput.name,
      startTime: searchInput.createTime[0],
      endTime: searchInput.createTime[1],
    };
  } else {
    datas = {
      name: searchInput.name,
    };
  }
  let res = await axios({
    method: "get",
    url: api.value + "/repairConsume/downloadRepairConsumeExcel",
    headers: {
      token: sessionStorage.getItem("token"),
      user_head: sessionStorage.getItem("userhead"),
    },
    params: datas,
    responseType: "blob",
  });
  console.log(res, "导出耗材");
  if (res.status == 200) {
    let name = `耗材数据`;
    var content = res.data;
    // var data = new Blob([content],{type:"application/octet-stream;charset=utf-8"});
    // var data = new Blob([content], {
    //   type: "application/vnd.ms-excel;charset=utf-8",
    // });
    var data = new Blob([content]);
    var downloadUrl = window.URL.createObjectURL(data);
    var anchor = document.createElement("a");
    anchor.href = downloadUrl;
    anchor.download = name + ".xlsx";
    anchor.click();
    window.URL.revokeObjectURL(data);
    ElMessage({
      type: "success",
      showClose: true,
      message: "导出成功",
      center: true,
    });
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: "导出失败",
      center: true,
    });
  }
};
//导出功能
const importExcel2 = async () => {
  let datas = {
    keyWord: searchInput2.name,
  };
  if (searchInput2.createTime) {
    datas.startTime = searchInput2.createTime[0];
    datas.endTime = searchInput2.createTime[1];
  }
  let res = await axios({
    method: "get",
    url: api.value + "/repairConsumables/downloadRepairConsumableExcel",
    headers: {
      token: sessionStorage.getItem("token"),
      user_head: sessionStorage.getItem("userhead"),
    },
    params: datas,
    responseType: "blob",
  });
  console.log(res, "导出耗材记录");
  if (res.status == 200) {
    let name = `耗材记录数据`;
    var content = res.data;
    // var data = new Blob([content],{type:"application/octet-stream;charset=utf-8"});
    // var data = new Blob([content], {
    //   type: "application/vnd.ms-excel;charset=utf-8",
    // });
    var data = new Blob([content]);
    var downloadUrl = window.URL.createObjectURL(data);
    var anchor = document.createElement("a");
    anchor.href = downloadUrl;
    anchor.download = name + ".xlsx";
    anchor.click();
    window.URL.revokeObjectURL(data);
    ElMessage({
      type: "success",
      showClose: true,
      message: "导出成功",
      center: true,
    });
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: "导出失败",
      center: true,
    });
  }
};
// 导入弹窗
const importFile = () => {
  importXlsx.value = true;
};
const closeXlsx = () => {
  importXlsx.value = false;
  upload.value.clearFiles();
  fileXlsx.value = "";
};
// 导出模板
const importTemp = async () => {
  let res = await axios({
    method: "get",
    url: api.value + "/repairConsume/downloadRepairConsumeModelExcel",
    headers: {
      token: sessionStorage.getItem("token"),
      user_head: sessionStorage.getItem("userhead"),
    },
    responseType: "blob",
  });
  console.log(res, "导出模板");
  if (res.status == 200) {
    let name = `耗材数据导入模板`;
    var content = res.data;
    var data = new Blob([content]);
    var downloadUrl = window.URL.createObjectURL(data);
    var anchor = document.createElement("a");
    anchor.href = downloadUrl;
    anchor.download = name + ".xlsx";
    anchor.click();
    window.URL.revokeObjectURL(data);
    ElMessage({
      type: "success",
      showClose: true,
      message: "导出成功",
      center: true,
    });
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: "导出失败",
      center: true,
    });
  }
};
// 添导入文件功能
const handleChange = (file, fileLists) => {
  console.log(file, "file11111");
  // let formData = new FormData(); //声明一个FormDate对象
  // formData.append("formFile", file.raw);
  // fileXlsx.value = formData;
  fileXlsx.value = file.raw;
};
// 可以获取文件参数(封面图上传图片)
const handleUpload = (file) => {
  console.log(file, "file22222");
};
// 移出文件
const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
  fileXlsx.value = "";
};
// 限制上传图片的大小类型
const beforeAvatarUpload = (rawFile) => {
  console.log(rawFile.type);
  if (
    rawFile.type !==
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
  ) {
    ElMessage.error("文件必须为xlsx格式!");
    return false;
  }
  return true;
};
// 上传文件时多次上传会替换前一个文件
const handleExceed = (files) => {
  console.log(files, "替换文件");

  upload.value.clearFiles();
  const file = files[0];
  upload.value.handleStart(file);

  fileXlsx.value = files.raw;
};
// 确定导入文件
const importSuc = async () => {
  console.log("确定导入");

  let data = new FormData(); //声明一个FormDate对象
  data.set("file", fileXlsx.value);

  let res = await axios({
    method: "post",
    url: api.value + "/repairConsume/importRepairConsumeExcel",
    headers: {
      token: sessionStorage.getItem("token"),
      user_head: sessionStorage.getItem("userhead"),
      "Content-Type": "multipart/form-data;charset=UTF-8",
    },
    data: data,
  });
  console.log(res);
  if (res.data.code == 200) {
    importXlsx.value = false;
    getList();
    ElMessage({
      type: "success",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  }
};

// 表格多选框多选框功能
const handleSelectionChange = (val) => {
  console.log(val);
  selectData.list = val;
};

// 表格斑马纹颜色修改
const tableRowClassName = ({ row, rowIndex }) => {
  if (rowIndex % 2 === 0) {
    return "even";
  } else if (rowIndex % 2 !== 0) {
    return "odd";
  }
  return "";
};
// 耗材管理分页
const handleCurrentChange = (value) => {
  // console.log(value);
  currentPage.value = value;
  getList(themeIndex.value);
};
//  耗材记录分页
const handleCurrentChange2 = (value) => {
  // console.log(value);
  currentPage2.value = value;
  getList(themeIndex.value);
};

onBeforeMount(() => {
  api.value = store.state.user.api;
  getList(themeIndex.value);
});
onUnmounted(() => {
  // document.removeEventListener("keyup", Enters);
});
</script>

<style scoped lang="scss">
.content-box {
  width: 97.5%;
  height: 89%;
  margin: 20px auto;
  background-color: #fff;
  color: #fff;
  display: flex;
  flex-direction: column;
  box-shadow: 0px 3px 10px rgba(213, 228, 252, 1);

  .left {
    // width: calc(100wh - 40px);
    display: flex;
    align-items: center;
    height: 60px;
    margin: 0 30px;
    border-bottom: 1px solid #ccc;
    color: rgb(0, 0, 0);
    font-size: 18px;
    font-weight: 600;

    span {
      margin-right: 20px;
      cursor: pointer;
    }

    .is_active {
      color: rgba(111, 182, 184, 1);
    }
  }

  .middle {
    width: 96%;
    margin: 0 auto;

    color: #000;

    // border-bottom: 1px solid rgb(231, 231, 231);
    .filter {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      margin: 10px 0 0 0;

      .search {
        color: #fff;
      }

      .condition {
        display: flex;
        align-items: center;
        margin: 10px 30px 10px 0;

        :deep(.el-input .el-input__inner) {
          font-size: 16px;
        }

        span {
          margin: 0 10px 0 0;
        }
      }
    }

    .gongneng {
      margin: 10px 0 20px 0;

      span {
        color: #fff;
      }
    }

    :deep(.cont) {
      width: 60%;
      margin: 20px auto;
    }

    :deep(.download) {
      display: flex;
      align-items: center;
      margin: 10px;
    }

    :deep(.download span) {
      font-size: 16px;
      margin-left: 20px;
    }

    :deep(.cont .el-button) {
      margin-left: 60px;
      margin-bottom: 30px;
    }

    :deep(.cont .accomplish) {
      width: 100%;
      display: flex;
      justify-content: center;
    }

    :deep(.cont .accomplish .el-button) {
      width: 50%;
      margin: 0;
    }
  }

  .footer {
    width: 96%;
    height: 550px;
    margin: 10px auto 30px;

    .el-table--fit {
      height: 100%;

      :deep(.el-table__header-wrapper) {
        background-color: #000;
        font-size: 16px;

        tr {
          color: #000;
        }
      }

      :deep(.el-table__row) {
        height: 50px;
        font-size: 16px;
        color: #000;
      }

      :deep(.el-table__row td) {
        padding: 0;
        border: 0;
      }

      .el-button--primary {
        margin-left: 5px;
      }

      :deep(.el-table__body .even) {
        background-color: #fff;
      }

      :deep(.el-table__body .odd) {
        background-color: rgba(240, 243, 247, 1);
      }

      :deep(.edit) {
        display: flex;
        align-items: center;
        justify-content: center;
        color: rgba(111, 182, 184, 1);
      }

      :deep(.look) {
        padding: 0 10px;
        cursor: pointer;
      }

      :deep(.look):hover {
        color: red;
      }
    }

    // 添加员工弹窗样式
    :deep(.addStaff) {
      //   height: 420px;
      border-radius: 11px;

      .el-dialog__header {
        border-radius: 11px 11px 0 0;
        background: rgba(237, 241, 245, 1);
        font-weight: 600;
        margin: 0;

        .el-dialog__headerbtn {
          outline: none;
        }
      }

      .el-dialog__body {
        padding: 30px 20px 10px 20px;

        .el-input {
          width: 200px;
        }

        .checkbox {
          .el-form-item__content {
            display: flex;
            flex-direction: column;
            align-items: flex-start;

            .el-checkbox-group {
              display: flex;
              flex-direction: column;
            }
          }
        }

        .options {
          .el-form-item__content {
            .queding {
              margin-left: 20px;
              color: #fff;
            }

            display: flex;
            flex-direction: row-reverse;
          }
        }
      }
    }

    // 导入弹窗样式
    :deep(.importXlsx) {
      //   height: 420px;
      border-radius: 11px;

      .el-dialog__header {
        border-radius: 11px 11px 0 0;
        background: rgba(237, 241, 245, 1);
        font-weight: 600;
        margin: 0;

        .el-dialog__headerbtn {
          outline: none;
        }
      }

      .el-dialog__body {
        padding: 20px 20px 10px 20px;

        .el_btn {
          display: flex;
          // align-items: center;
          // justify-content: space-between;
        }

        .avatar-uploader {
          width: 100%;
          margin: 0 10px;
        }

        .options {
          margin: 15px 0;

          .queding {
            margin-left: 20px;
            color: #fff;
          }

          display: flex;
          flex-direction: row-reverse;
        }
      }
    }
  }

  .pageSize {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: 0 30px;

    span {
      color: #000;
    }

    .el-pagination {

      // width: 1600px;
      :deep(.el-pagination__total) {
        color: #000;
      }

      :deep(.el-pagination__goto) {
        color: #000;
      }

      :deep(.el-pagination__classifier) {
        color: #000;
      }

      :deep(.el-input__wrapper) {
        border: 1px solid rgba(0, 0, 0, 1);
        border-radius: 5px;
        box-shadow: none;
      }

      :deep(.el-pager li) {
        margin: 0 5px;
        border: 1px solid rgba(0, 0, 0, 1);
        border-radius: 5px;
        background-color: transparent;
      }

      :deep(.el-pager li.is-active) {
        background-color: rgba(111, 182, 184, 1);
      }

      :deep(.btn-prev) {
        margin-right: 5px;
        border: 1px solid rgba(0, 0, 0, 1);
        border-radius: 5px;
        background-color: transparent;
      }

      :deep(.btn-next) {
        margin-left: 5px;
        border: 1px solid rgba(0, 0, 0, 1);
        border-radius: 5px;
        background-color: transparent;
      }
    }
  }
}

.el-input {
  width: 192px;
}
</style>
