<script setup lang="ts">
import { queryProcessGroup, saveProcessGroup } from "@/api/process";

const groupData = ref<Record<string, string[]>>({});
const nodesData = ref<any[]>([]);
const routeIdA = ref("");

const drawer2 = ref(false);

const emits = defineEmits(["success"]);

function cancelClick() {
  drawer2.value = false;
}
function confirmClick() {
  let dict: Record<string, string[]> | undefined = {};
  for (let key in groupData.value) {
    let array = groupData.value[key];
    dict[key] = array.map((id: string) => {
      return {
        id: id,
      };
    });
  }
  let p = {
    group: { ...dict },
    routeId: routeIdA.value,
  };

  saveProcessGroup(p).then(() => {
    emits("success");
    ElMessage.success("保存成功");
    drawer2.value = false;
  });
}

const stateUsable = ref(null);
const startGroup = async (nodes: any[], routeId: string, usable: any) => {
  stateUsable.value = usable;
  nodesData.value = markRaw(nodes);
  if(nodesData.value){
    try{
      nodesData.value = nodesData.value.slice().sort((a, b) => a.lineTag.localeCompare(b.lineTag));
      nodesData.value = nodesData.value.slice().sort((a, b) => a.lineTag.length - b.lineTag.length);
    }catch (e){}
  }
  routeIdA.value = routeId;

  drawer2.value = true;
  let res = await queryProcessGroup(routeId);
  let dict: Record<string, string[]> | undefined = {};
  for (let key in res.data) {
    let array = res.data[key];
    dict[key] = array.map((item: any) => {
      return item.id;
    });
  }

  groupData.value = dict;
};

defineExpose({
  startGroup,
});

import type { CheckboxValueType } from "element-plus";
import {number} from "echarts";

const checkAll = ref(false);
const indeterminate = ref(false);
const value = ref<CheckboxValueType[]>([]);

watch(value, (val) => {
  if (val.length === 0) {
    checkAll.value = false;
    indeterminate.value = false;
  } else if (val.length === cities.value.length) {
    checkAll.value = true;
    indeterminate.value = false;
  } else {
    indeterminate.value = true;
  }
});

const handleCheckAll = (val: CheckboxValueType) => {
  indeterminate.value = false;
  // if (val) {
  //   value.value = cities.value.map((_) => _.value);
  // } else {
  //   value.value = [];
  // }
};

// 新增分组相关
const input3 = ref("");
const addGroup = () => {
  if (!input3.value) {
    ElMessage.error("请输入分组名称！");
    return;
  }
  if (groupData.value.hasOwnProperty(input3.value)) {
    ElMessage.error("分组名称重复");
  } else {
    groupData.value[input3.value] = [];
  }
};

// 新增全选相关
const checked = ref<boolean>();
const selectAll = (key: string) => {
  if (checked.value) {
    groupData.value[key] = [];
    nodesData.value.map((item) => {
      groupData.value[key].push(item.operationId);
    });
  } else {
    groupData.value[key] = [];
  }
};

const changeChecked = (key: string) => {
  if (groupData.value[key].length === nodesData.value.length) {
    checked.value = true;
  } else {
    checked.value = false;
  }
};
</script>

<template>
  <el-drawer v-model="drawer2" :size="900">
    <template #header>
      <h4>将工序进行分组</h4>
    </template>
    <template #default>
      <el-row :gutter="20">
        <el-input
          v-model="input3"
          clearable
          placeholder="请输入分组名称"
          style="width: 70%"
        >
        </el-input>
        <el-button @click="addGroup" type="primary">添加分组</el-button>
      </el-row>

      <div v-for="key in new Map(Object.entries(groupData)).keys()" :key="key">
        <div class="name-container">
          <div class="group-name">{{ key }}</div>
          <el-button v-if="stateUsable === '0' || stateUsable === 'null'" link type="danger"
                     @click="() => delete groupData[key]"
            >删除</el-button
          >
        </div>

        <el-select
          v-model="groupData[key]"
          :disabled="stateUsable === '1'"
          multiple
          clearable
          filterable
          placeholder="请选择工序"
          popper-class="custom-header"
          @click="changeChecked(key)"
        >
          <!--          <template #header>-->
          <!--            <el-checkbox-->
          <!--              v-model="checkAll"-->
          <!--              :indeterminate="indeterminate"-->
          <!--              @change="handleCheckAll"-->
          <!--            >-->
          <!--              All-->
          <!--            </el-checkbox>-->
          <!--          </template> -->
          <template #header>
            <el-checkbox v-model="checked" @change="selectAll(key)"
              >全选</el-checkbox
            >
          </template>
          <el-option
            v-for="item in nodesData"
            :key="item.operationId"
            :label="item.operationName + '（' + item.lineTag + '）'"
            :value="item.operationId"
          />
        </el-select>
      </div>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancelClick">取消</el-button>
        <el-button type="primary" @click="confirmClick">保存</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<style scoped lang="scss">
.name-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 15px;
}

.group-name {
  font-size: 16px;
  font-weight: bold;
}
</style>
