<template>
  <!-- 添加或修改项目信息对话框 -->
  <el-drawer
      v-model="visible"
      size="80%"
      direction="rtl"
      :close-on-press-escape="false"
  >
    <div class="page-container form-container">
      <div class="form-btns-container">
        <span class="title-label"
        ><el-icon>
            <Document/>
          </el-icon>
          资源组详情</span
        >
        <el-button
            type="primary"
            icon="Check"
            style="margin-right: 10px"
            @click="handleSave"
        >保 存
        </el-button
        >
        <el-button icon="Close" @click="handleCancel">取 消</el-button>
      </div>
      <!-- 主表 -->
      <el-form
          ref="formRef"
          class="master-container"
          :model="form"
          label-width="120px"
          :rules="rules"
          :show-message="true"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="资源组编号:" prop="code">
              <el-input
                  v-model.trim="form.code"
                  placeholder="请输入资源组编号"
                  :clearable="true"
                  style="width: 280px"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 搜索区域 -->
      <el-form class="list-search-container" :inline="true">
        <el-form-item class="section-title" label="资源组明细"/>
        <el-form-item>
          <el-button
              type="warning"
              icon="Plus"
              @click="handleOpenPerson('person')"
          >添加人员
          </el-button
          >
          <el-button
              type="success"
              icon="Plus"
              @click="handleOpenPerson('equipment')"
          >添加设备
          </el-button
          >
          <el-button
              type="danger"
              icon="Delete"
              :disabled="selections.length == 0"
              @click="handleDelete"
          >批量删除
          </el-button
          >
        </el-form-item>
      </el-form>
      <!-- 列表区 -->
      <div class="el-table-container">
        <el-table
            ref="equipmentTable"
            v-loading="loading"
            row-key="id"
            @selection-change="handleSelectionChange"
            :data="form.groupDetailList"
            height="100%"
        >
          <el-table-column type="selection" width="40" align="center"/>
          <el-table-column label="资源编码" prop="commonCode" align="center"/>
          <el-table-column label="资源名称" prop="commonName" align="center"/>
          <el-table-column label="资源类别" prop="commonType" align="center">
            <template #default="scope">
              <dict-tag
                  :options="resource_group_detail"
                  :value="scope.row.commonType"
              />
            </template>
          </el-table-column>
          <el-table-column
              fixed="right"
              label="操作"
              align="center"
              width="140px"
          >
            <template #default="scope">
              <el-button
                  link
                  type="danger"
                  icon="Delete"
                  @click="handleDeleteResource(scope.row)"
              >删除
              </el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <person
          ref="personRef"
          :multiple="true"
          :multipleSelected="handleResourcePersonMultipleSelected"
      />
      <equipment
          ref="equipmentRef"
          :multiple="true"
          :multipleSelected="handleResourceMultipleSelected"
      />
    </div>
  </el-drawer>
</template>
<script setup>
import {
  getResourceGroup,
  addResourceGroup,
} from "@/api/business/resourceGroup";
import person from "@/views/dialog/person.vue";
import equipment from "@/views/dialog/equipment.vue";
import {checkUseEquipment} from "@/api/business/daywork";

const {proxy} = getCurrentInstance();
const emit = defineEmits(["handleSaveResourceSuccess"]);
/** 字典数组区 */
const {resource_group_detail} = proxy.useDict("resource_group_detail");
/** 表单抽屉 页变量 */
const selections = ref([]);
const loading = ref(false);
const personRef = ref(null);
const equipmentRef = ref(null);
const visible = ref(false);
/** 查询对象 */
const data = reactive({
  form: {
    groupDetailList: [],
    code: "",
    remark: "",
  },
  rules: {
    code: [{required: true, message: "资源组编码不能为空", trigger: "blur"}],
  },
});
const {form, rules} = toRefs(data);

/***********************  方法区  ****************************/
/** 打开抽屉 */
const open = (row) => {
  reset();
  loading.value = true;
  form.value.deptId = row.deptId;
  if (row.id) {
    form.value = row;
    console.log(form.value.id);
    getResourceGroup(form.value.id).then((res) => {
      if (res.code == 200) {
        form.value = res.data;
      }
    });
  }
  loading.value = false;
  visible.value = true;
};

/**
 * 列表checkbox列选择 事件
 */
function handleSelectionChange(selection) {
  selections.value = selection;
}

/**打开员工/设备弹窗 */
function handleOpenPerson(type) {
  if (type === "person") {
    var userInfo = {};
    userInfo.identifying = false;
    userInfo.deptId = form.value.deptId;
    userInfo.userIds = [];
    form.value.groupDetailList.map((item) => {
      if (item.commonType === "person") {
        userInfo.userIds.push(item.commonCode);
      }
    });
    proxy.$refs.personRef.open(userInfo);
  } else if (type === "equipment") {
    var equipmentInfo = {};
    equipmentInfo.deptId = form.value.deptId;
    equipmentInfo.equipmentCodeIds = [];
    form.value.groupDetailList.map((item) => {
      if (item.commonType === "equipmentDetail") {
        equipmentInfo.equipmentCodeIds.push(item.commonCode);
      }
    });
    proxy.$refs.equipmentRef.open(equipmentInfo);
  }
}

/**
 * 资源多选带回
 */
function handleResourceMultipleSelected(section) {
  for (var i = 0; i < section.length; i++) {
    var item = {};
    item.commonId = section[i].id;
    item.commonCode = section[i].equipmentCode;
    item.commonName = section[i].equipmentName;
    item.commonType = "equipmentDetail";
    form.value.groupDetailList.push(item);
  }
}

/**批量删除 */
function handleDelete() {
  checkUseEquipment(selections.value).then(res => {
    if(res.code == 200) {
        form.value.groupDetailList = form.value.groupDetailList.filter(
      (item) => !selections.value.some((selectedItem) => selectedItem === item)
  );
    }
  })

}

/**人员多选带回 */
function handleResourcePersonMultipleSelected(section) {
  console.log(section);
  for (var i = 0; i < section.length; i++) {
    let item = {};
    item.commonId = section[i].userId;
    item.commonCode = section[i].userName;
    item.commonName = section[i].nickName;
    item.commonType = "person";
    form.value.groupDetailList.push(item);
  }
}

/**
 * 对话框关闭 事件
 */
function close() {
  reset();
  visible.value = false;
}

/** 表单重置 */
function reset() {
  form.value = {
    code: null,
    remark: null,
    groupDetailList: [],
  };
  proxy.resetForm("formRef");
}

/** 提交按钮 */
const handleSave = () => {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      if (!form.value.groupDetailList) {
        proxy.$modal.msg("资源组信息不能为空");
      } else {
        var personInfo = [];
        var equipmentInfo = [];
        form.value.groupDetailList.map((item) => {
          if (item.commonType === "person") {
            personInfo.push(item.commonCode);
          }
          if(item.commonType === "equipmentDetail") {
            equipmentInfo.push(item.commonCode);
          }
        });
        if (personInfo.length == 0) {
          proxy.$modal.msg("至少有一名资源组成员");
        }else if(equipmentInfo.length == 0) {
          proxy.$modal.msg("至少有一台设备");
        }
        else {
          addResourceGroup(form.value).then((res) => {
            if (res.code == 200) {
              emit("handleSaveResourceSuccess");
              close();
            }
          });
        }
      }
    }
  });
};

/**删除资源组明细 */
function handleDeleteResource(row) {
  //删除设备判断该设备是否报工，如果已经报工了，不能删除
  checkUseEquipment([row]).then(res => {
    if(res.code == 200) {
      form.value.groupDetailList.splice(form.value.groupDetailList.indexOf(row), 1);
    }
  })
  
}

/** 取消按钮 */
const handleCancel = () => {
  visible.value = false;
  reset();
};

/** 暴露给父组件的方法 */
defineExpose({
  open,
});
</script>
