<template>
  <div class="page-container row-container">
    <!-- 左侧区域 -->
    <section class="list-part-container column-container" style="flex: 3">
      <!-- 搜索区域 -->
      <el-form class="list-search-container" :inline="true" style="display: flex">
        <el-form-item class="section-title" label="包装线列表" />
        <el-form-item class="section-title" label="请选择当前工段：">
          <el-select-v2 v-model="queryDeptParams.deptId" :options="deptList" placeholder="请选择工段" style="width: 100px"
            @change="handleDeptChange" />
        </el-form-item>
        <!-- :disabled="packageResourceGroups.length === 0" -->
        <el-button type="primary" icon="Plus" @click="handleAdd()"
          v-hasPermi="['business:packageResourceGroup:add']">新增</el-button>
        <el-button type="info" icon="Search" @click="handleFlash()"
          v-hasPermi="['business:packageResourceGroup:list']">刷新</el-button>
      </el-form>
      <!-- 列表区 -->
      <div class="el-table-container">
        <div class="el-table-inner-container">
          <el-table ref="workSectionTable" v-loading="workSectionLoading" :data="packageResourceGroups" row-key="id"
            height="100%" highlight-current-row @current-change="handleWorkSectionChange">
            <el-table-column label="行号" type="index" width="50" align="center" />
            <el-table-column label="工段编码" prop="deptCode" width="120" align="center">
              <template #default="scope">
                <el-input v-if="scope.row.editStatus" v-model="scope.row.deptCode" readonly>
                  <template #append>
                    <el-button type="primary" icon="Search" @click="showDeptChoiceDialog(scope.row)"></el-button>
                  </template>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column label="工段名称" prop="deptName" align="center" />
            <el-table-column label="工段号" prop="deptNo" width="80" align="center">
              <template #default="scope">
                <el-input v-if="scope.row.editStatus" v-model="scope.row.deptNo" maxlength="1" />
              </template>
            </el-table-column>
            <el-table-column label="包装线号" prop="packageLineNo" align="center">
              <template #default="scope">
                <el-input v-if="scope.row.editStatus" v-model="scope.row.packageLineNo" maxlength="1" />
              </template>
            </el-table-column>
            <el-table-column label="包装线名" prop="name" align="center">
              <template #default="scope">
                <el-input v-if="scope.row.editStatus" v-model.trim="scope.row.name" />
              </template>
            </el-table-column>
            <el-table-column label="年" prop="year" align="center">
              <template #default="scope">
                <el-input v-if="scope.row.editStatus" v-model="scope.row.year" maxLength="2" />
              </template>
            </el-table-column>
            <el-table-column label="当前编号" prop="code" align="center">
              <template #default="scope">
                <el-input v-if="scope.row.editStatus" v-model="scope.row.code" />
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="220">
              <template #default="scope">
                <template v-if="!scope.row.editStatus">
                  <el-button type="primary" link icon="Edit" @click="handleShowProcessFormDialog(scope.row)"
                    v-hasPermi="['business:packageResourceGroup:edit']">编辑</el-button>
                  <el-button type="danger" link icon="Delete" @click="handleDeleteGroup(scope.row, scope.$index)"
                    v-hasPermi="['business:packageResourceGroup:remove']">删除</el-button>
                </template>
                <template v-else>
                  <el-button type="success" link icon="Finished" @click="handleGroupSave(scope.row)"
                    v-hasPermi="['business:packageResourceGroup:edit']">保存</el-button>
                  <el-button type="info" link icon="Close" @click="handleGroupCancel(scope.row, scope.$index)"
                    v-hasPermi="['business:packageResourceGroup:remove']">取消</el-button>
                </template>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </section>
    <!-- 右侧区域 -->
    <section class="list-part-container row-container" style="flex: 3">
      <el-form class="list-search-container" :inline="true">
        <el-form-item class="section-title" label="包装线员工" />
        <el-form-item>
          <el-button type="primary" icon="Plus" :disabled="packageResourceGroups.length === 0"
            @click="handleShowEmployeeDialog()" v-hasPermi="['business:packageResourceGroup:userAdd']">新增</el-button>
          <el-button type="danger" icon="Delete" @click="handledDelPackageLineEmployee"
            :disabled="!(deptProcessIds && deptProcessIds.length > 0)"
            v-hasPermi="['business:packageResourceGroup:userRemove']">
            删除
          </el-button>
        </el-form-item>
        <el-form-item style="margin: 0">
          <el-button type="info" icon="Search" :disabled="packageResourceGroups.length === 0"
            @click="handleQueryProcess">刷新</el-button>
        </el-form-item>
      </el-form>
      <div class="el-table-container">
        <div class="el-table-inner-container">
          <el-table ref="workEmployeeTable" v-loading="deptProcessLoading" :data="userList" row-key="id" height="100%"
            @selection-change="deptProcessSelectionChange">
            <el-table-column type="selection" width="40" align="center" :reserve-selection="true" />
            <el-table-column label="行号" type="index" width="50" align="center" />
            <el-table-column label="员工号" prop="userName" align="center" />
            <el-table-column label="员工姓名" prop="nickName" align="center" />
          </el-table>
        </div>
      </div>
      <pagination v-show="deptProcessTotal > 0" :total="deptProcessTotal" v-model:page="queryDeptProcessParams.pageNum"
        v-model:limit="queryDeptProcessParams.pageSize" @pagination="getDetails"
        layout="total, sizes, prev, next, jumper" />
    </section>
    <EmployeeChoiceDialog ref="employeeChoiceDialogRef" :multiple="true"
      :multipleSelected="handleEmployeeMultipleSelected" />
    <DeptChoiceDialog ref="deptChoiceDialogRef" @handleSelectBelongingDept="handleSelectBelongingDept" />
  </div>
</template>

<script setup>
import {
  listResourceGroup,
  delResourceGroup,
} from "@/api/business/resourceGroup";
import {
  listGroup,
  addGroup,
  updateGroup,
  delGroup,
  listDetails,
  addDetails,
} from "@/api/business/packageResourceGroup";
import { delDetail } from "@/api/business/packageResourceGroupDetail";
import { getDeptListByUserIdInPackage } from "@/api/business/planDetailSubDetail.js";
import resourceGroupForm from "./form";
import userInfo from "@/store/modules/user";
import EmployeeChoiceDialog from "./EmployeeChoiceDialog.vue";
import DeptChoiceDialog from "./DeptChoiceDialog.vue";
const { proxy } = getCurrentInstance();
/** 查询对象 */
const data = reactive({
  form: {},
  queryDeptParams: {
    deptName: "",
    deptCode: "",
    deptId: "",
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    code: "",
  },
  queryResourceGroupDetailParams: {
    code: "",
    productionResourceGroupId: "",
  },
  queryDeptProcessParams: {
    pageNum: 1,
    pageSize: 10,
  },
});

const employeeChoiceDialogRef = ref(null);
const deptChoiceDialogRef = ref(null);

const {
  queryParams,
  queryDeptProcessParams,
  queryDeptParams,
  queryResourceGroupDetailParams,
} = toRefs(data);
/** 页面变量 */
/**工段 */
const packageResourceGroups = ref([]);
const workSectionLoading = ref(false);
const currentGroup = ref({});
const groupList = ref([]);
const groupLoading = ref(false);
/**资源组明细 */
const groupDetailLoading = ref(false);
const deptList = ref([]);
/**工序 */
const userList = ref([]);
const deptProcessLoading = ref(false);
const deptProcessTotal = ref(0);
const deptProcessIds = ref([]);
const single = ref(true);

/****************************  工段方法区  ****************************/

/** 获取工段列表 */
function getList() {
  workSectionLoading.value = true;
  //如果当前登录人不是管理员传true；否则传false
  queryDeptParams.value.getType = true;
  listGroup(queryDeptParams.value).then((res) => {
    packageResourceGroups.value = res.rows.map((e) => ({
      ...e,
      editStatus: false,
    }));
    if (packageResourceGroups.value.length > 0) {
      proxy.$refs.workSectionTable.setCurrentRow(
        packageResourceGroups.value[0]
      );
    } else {
      packageResourceGroups.value = [];
    }
    workSectionLoading.value = false;
  });
}
//切换工段
function handleDeptChange() {
  getList();
}
/**工段点击事件 */
const handleWorkSectionChange = (row) => {
  queryParams.value.code = "";
  queryResourceGroupDetailParams.value.commonCode = "";
  queryDeptProcessParams.value.processAlias = "";
  if (row && row.id != null) {
    currentGroup.value = row;
    queryParams.value.deptId = row.id;
    getDetails();
  } else {
    userList.value = [];
    deptProcessTotal.value = 0;
  }
};

/*******************************工序方法区*********************************** */
/**获取工序 */
function getDeptList() {
  getDeptListByUserIdInPackage().then((response) => {
    deptList.value = response.data.rows;
    if (deptList.value.length > 0) {
      console.log(userInfo().user.userId);
      // if(userInfo().user.userId == 1){
      //   deptList.value.unshift({
      //     label: '全部',
      //     value: '-1'
      //   })
      // }
      queryDeptParams.value.deptId = deptList.value[0].value;
      getList();
    } else {
      packageResourceGroups.value = [];
      userList.value = [];
    }
  });
}
function handleFlash() {
  if (queryDeptParams.value.deptId != "") {
    getList();
  }
}

function checkNameUniqueness(currentRow) {
  const { deptCode, name } = currentRow;
  const otherRows = packageResourceGroups.value.filter(
    (row) => row.id !== currentRow.id && row.deptCode === deptCode
  );
  return otherRows.every((row) => row.name !== name);
}
const getDetails = () => {
  deptProcessIds.value = [];
  deptProcessLoading.value = true;
  queryDeptProcessParams.value.packageResourceGroupId = currentGroup.value.id;
  listDetails(queryDeptProcessParams.value).then((res) => {
    userList.value = res.rows;
    deptProcessLoading.value = false;
    deptProcessTotal.value = res.total;
  });
};
/**工序搜索框 */
function handleQueryProcess() {
  getDetails();
}
/** 打开工序对话框事件 */
function handleShowProcessFormDialog(row) {
  row.editStatus = !row.editStatus;
}

//工段工序多选框选中数据
function deptProcessSelectionChange(selection) {
  deptProcessIds.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
}

/**删除工序工段表数据 */
function handledDelPackageLineEmployee() {
  console.log(deptProcessIds.value);
  if (deptProcessIds.value && deptProcessIds.value.length > 0) {
    proxy.$modal
      .confirm("是否确认删除选中的数据项？")
      .then(function () {
        return delDetail(deptProcessIds.value);
      })
      .then(() => {
        deptProcessIds.value = [];
        proxy.$refs.workEmployeeTable.clearSelection();
        getDetails();
        proxy.$modal.msgSuccess("删除成功！");
      })
      .catch((e) => {
        proxy.$modal.msg("操作失败！");
      });
  }
}

function handleDeleteGroup(row, index) {
  proxy.$modal
    .confirm("是否确认删除选中的数据项？")
    .then(function () {
      if (row != null && row.id != null)
        return delGroup(row.id).then((res) => {
          getList();
        });
      else packageResourceGroups.value.splice(index, 1);
    })
    .then(() => {
      getDetails();
      proxy.$modal.msgSuccess("删除成功！");
    });
}

function handleShowEmployeeDialog() {
  employeeChoiceDialogRef.value.open();
}

function showDeptChoiceDialog(row) {
  currentGroup.value = row;
  deptChoiceDialogRef.value.open();
}

function handleAdd() {
  packageResourceGroups.value.splice(0, 0, {
    editStatus: true,
    year: proxy.moment().format("YY"),
    code: "000000",
  });
  userList.value = [];
  deptProcessTotal.value = 0;
}

function handleSelectBelongingDept(info) {
  currentGroup.value.deptId = info.deptId;
  currentGroup.value.deptName = info.deptName;
  currentGroup.value.deptCode = info.deptCode;
}

function handleGroupCancel(row, index) {
  if (row.id != null) {
    row.editStatus = false;
  } else {
    packageResourceGroups.value.splice(index, 1);
  }
}

function handleGroupSave(row) {
  // 判断工段包装线名都不能为空
  if (row.name == null || row.name == "") {
    proxy.$modal.msgError("包装线名不能为空");
    return;
  }
  if (row.deptId == null) {
    proxy.$modal.msgError("工段不能为空");
    return;
  }
  if (row.year == null || row.year == "") {
    proxy.$modal.msgError("年份不能为空");
    return;
  }
  if (row.deptNo == null || row.deptNo == "") {
    proxy.$modal.msgError("工段号不能为空");
    return;
  }
  if (row.packageLineNo == null || row.packageLineNo == "") {
    proxy.$modal.msgError("包装线号不能为空");
    return;
  }
  if (row.code == null || row.code == "") {
    proxy.$modal.msgError("当前编码不能为空");
    return;
  }
  // 判断年是否是2位数字
  if (!isNaN(Number(row.year)) && row.year.length > 2) {
    proxy.$modal.msgError("年份不能为非数字或大于2位");
    return;
  }
  // 判断code只能是小于6位数字
  if (!isNaN(Number(row.code)) && row.code.length > 6) {
    proxy.$modal.msgError("当前编码不能为非数字或大于6位");
    return;
  }

  if (!checkNameUniqueness(row)) {
    proxy.$message.error("相同工段的包装线名称不能重复，请修改名称后再保存。");
    return;
  }

  if (row.id == null) {
    addGroup(row).then(() => {
      getList();
    });
  } else {
    updateGroup(row).then(() => {
      getList();
    });
  }
}

function handleEmployeeMultipleSelected(infos) {
  const data = {
    ...currentGroup.value,
    employees: infos,
  };
  addDetails(data).then((res) => {
    if (res.code == 200) {
      getDetails();
    }
  });
}

onMounted(() => {
  getDeptList();
});
</script>
