<template>
  <div class="page-container column-container">
    <!-- 搜索区 -->
    <el-form class="list-search-container" :model="queryParams" ref="queryRef" :inline="true">
      <el-form-item label="产品描述：">
        <el-input placeholder="请输入产品描述" v-model="queryParams.productDescription" style="width: 150px" clearable
          @keyup.enter="handleQuerydaywork" @keydown.enter.prevent />
      </el-form-item>
      <el-form-item label="生产计划单号：">
        <el-input placeholder="请输入生产计划单号" v-model="queryParams.productionPlanNo" style="width: 120px" clearable
          @keyup.enter="handleQuerydaywork" @keydown.enter.prevent />
      </el-form-item>
      <!-- <el-form-item label="序号：">
        <el-input placeholder="请输入序号" v-model.trim="queryParams.lineNumber" style="width: 130px" clearable
          @keyup.enter="handleQuerydaywork" @keydown.enter.prevent />
      </el-form-item> -->
      <el-form-item label="批次号：">
        <el-input placeholder="请输入批次号" v-model="queryParams.lotCode" style="width: 130px" clearable
          @keyup.enter="handleQuerydaywork" @keydown.enter.prevent />
      </el-form-item>
      <el-form-item label="工段：">
        <!-- <el-select-v2 v-model="queryParams.deptId" :options="deptList" placeholder="请选择工段" style="width: 140px" /> -->
        <el-autocomplete v-model.trim="deptName" clearable :fetch-suggestions="queryDeptSearchAsync" placeholder="请选择工段"
          @select="handleDeptSelect" style="width: 140px" @clear="handleClearDept">
          <template #default="{ item }">
            <div style="
                display: flex;
                flex-direction: row;
                justify-content: space-between;
              ">
              <div class="name" style="font-size: 12px">
                {{ item.deptName }}
              </div>
            </div>
          </template>
        </el-autocomplete>
      </el-form-item>
      <el-form-item label="标识：">
        <el-select style="width: 160px" multiple v-model="queryParams.flags" collapse-tags collapse-tags-tooltip
          clearable placeholder="请选择标识" @change="handleFlagChange">
          <el-option v-for="item in is_identification" :key="item.value" :label="item.label"
            :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工序：">
        <!-- <el-select-v2 v-model="processAlias" :options="processList" placeholder="请选择工序" style="width: 140px"
          @change="handleProcessChange" /> -->
        <el-autocomplete v-model.trim="processAlias" clearable :fetch-suggestions="queryProcessSearchAsync"
          placeholder="请选择工序" @select="handleProcessSelect" style="width: 140px" @clear="handleClearProcess">
          <template #default="{ item }">
            <div style="
                display: flex;
                flex-direction: row;
                justify-content: space-between;
              ">
              <div class="name" style="font-size: 12px">
                {{ item.label }}
              </div>
            </div>
          </template>
        </el-autocomplete>
      </el-form-item>
      <el-form-item label="时间：">
        <el-date-picker v-model="queryParams.startTime" type="date" value-format="YYYY-MM-DD" :editable="false"
          :clearable="false" placeholder="请选择开始时间" style="width: 130px" @change="handleDateChange" />
        <span>到</span>
        <el-date-picker v-model="queryParams.endTime" type="date" value-format="YYYY-MM-DD" :editable="false"
          :clearable="false" placeholder="请选择结束时间" style="width: 130px" @change="handleDateChange" />
      </el-form-item>
      <el-form-item>
        <el-button type="info" icon="Search" @click="handleQuerydaywork">搜索</el-button>
      </el-form-item>
      <div style="margin-top: 20px">
        <!-- <el-button type="primary" @click="handleWasteRecycling"
          :disabled="selections.length == 0 || selections.length > 1"
          v-hasPermi="['business:lot:wasteRecycling']">添加废品回用</el-button> -->
        <el-button :disabled="selections.length !== 1" type="primary" @click="showInBatch"
          v-hasPermi="['business:lot:inBatch']">分批</el-button>
        <el-button type="primary" :disabled="once" @click="handleOnceSingleChange"
          v-hasPermi="['business:lot:onceSingleChange']">单批单改</el-button>
        <el-button type="primary" :disabled="multi" @click="handleMultiSingleChange"
          v-hasPermi="['business:lot:multiSingleChange']">多批单改</el-button>
      </div>
    </el-form>
    <!-- 列表区 -->
    <div class="el-table-container">
      <div class="el-table-inner-container">
        <el-table ref="dayworkTable" v-loading="loading" row-key="lotId" @selection-change="handleSelectionChange"
          height="100%" :data="lotList">
          <el-table-column type="selection" width="40" align="center" />
          <el-table-column label="客户简称" prop="companyAlias" width="120" align="center" />
          <el-table-column label="生产计划单号" width="100" prop="productionPlanNo" align="center" />
          <el-table-column label="序号" width="60" prop="lineNumber" align="center" />

          <el-table-column label="批次号" prop="lotCode" align="center" width="150px">
            <template #default="scope">
              <el-button link type="primary" @click="handleColumnClick(scope.row.lotCode)"><span>{{ scope.row.lotCode
                  }}</span></el-button>
            </template>
          </el-table-column>
          <el-table-column label="产品描述" prop="productDescription" align="center" />
          <el-table-column label="图纸版本" width="80" prop="technologyVersion" align="center" />
          <el-table-column label="投产量" width="100" prop="productionQuantity" align="center" />
          <el-table-column label="下达日期" prop="createTime" width="100" align="center">
            <template #default="scope">
              <span>{{
                proxy.moment(scope.row.createTime).format("YYYY-MM-DD")
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="当前工段" width="100" prop="deptName" align="center" />
          <el-table-column label="当前工序" width="120" prop="processAlias" align="center" />
          <el-table-column label="标识" width="300" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.isWaste == 1" class="spacing" type="danger">{{ "批废" }}</el-tag>
              <el-tag v-if="scope.row.isAmend == 1" class="spacing" type="danger">{{ "工艺修改" }}</el-tag>
              <el-tag v-if="scope.row.isWasteRecycling == 1" class="spacing" type="primary">{{ "废品回用" }}</el-tag>
              <el-tag v-if="scope.row.isSuperaddition == 1" class="spacing" type="warning">{{ "追增" }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="母批号" prop="fromCode" align="center">
            <template #default="scope">
              <el-button link type="primary" width="150px" @click="handleColumnClick(scope.row.fromCode)"><span>{{
                scope.row.fromCode }}</span></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getLot" />
    <waste-recycling-dialog ref="wasteRecyclingDialogRef" @handleSaveSuccess="getLot"></waste-recycling-dialog>
    <InBatchesDialog ref="inBatchesDialogRef" :getList="handleQuerydaywork" />
    <once-change ref="onceChangeRef" @handleSaveSuccess="getLot" />
    <multi-change ref="multiChangeRef" @handleSaveSuccess="getLot" />
  </div>
</template>
<script setup name="ProductionPlan">
import { listDept } from "@/api/system/dept";
import { getDeptList } from "@/api/system/dept.js";
import { getLotList, getProcessList } from "@/api/business/lot.js";
import wasteRecyclingDialog from "./DialogWasteRecycling.vue";
import router from "@/router";
import multiChange from "@/views/business/reviseBath/multiSingleChangeDialog.vue";
import onceChange from "@/views/business/reviseBath/onceSingleChangeDialog.vue";
import InBatchesDialog from "@/views/business/lot/InBatchesDialog.vue";
import { ref } from "vue";
import lotStore from "@/store/modules/lot";

const route = useRoute();
const { proxy } = getCurrentInstance();
/** 字典数组区 */
const { is_identification } = proxy.useDict("is_identification");
/** 表单抽屉 页变量 */
const inBatchesDialogRef = ref(null);
const loading = ref(false);
const once = ref(true); //单批单改按钮是否可点击
const multi = ref(true); //多批单改按钮是否可点击
const lotList = ref([]);
const total = ref(0);
const processAlias = ref("");
const deptName = ref("");
const visible = ref(false);
const selections = ref([]);
const processList = ref([]);
const deptList = ref([]);

/** 查询对象 */
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  productDescription: "",
  productionPlanNo: "",
  lotCode: "",
  deptId: null,
  flag: null,
  lineNumber: null,
  deptName: "",
  startTime: "",
  endTime: "",
});
const queryDeptParams = ref({
  lineNumber: "",
  productionPlanNo: "",
});

/***********************  方法区  ****************************/
/** 打开抽屉 */
function getDept() {
  getNowDate();
  getPassDate();
  //获取工段信息
  queryParams.value.productionPlanNo = "";
  queryParams.value.lineNumber = null;
  getDeptList({ type: 0, isWorkSection: 1 }).then((res) => {
    if (res.code == 200) {
      deptList.value = res.data;
    }
    if (lotStore().lotQueryParams != null) {
      deptName.value = lotStore().lotQueryParams.deptName;
    }
  });

  getProcess();
  if (route.params.productionPlanNo != ":productionPlanNo") {
    queryParams.value.productionPlanNo = route.params.productionPlanNo;
    queryParams.value.lineNumber = route.params.lineNumber;
  }

  getLot();
  visible.value = true;
}
function handleDateChange() {
  console.log(queryParams.value.startTime);
  console.log(queryParams.value.endTime);
}
function getProcess() {
  if (lotStore().lotQueryParams != null) {
    processAlias.value = lotStore().lotQueryParams.processAlias;
  }
  getProcessList(queryParams.value).then((response) => {
    processList.value = response.data;
  });
}

/** 多批单改操作 */
function handleMultiSingleChange() {
  if (selections.value.every((item) => item.isWaste == 1)) {
    proxy.$message.error("批废不能再进行操作");
    return;
  }

  //判断是否同一计划单且当前工序相同的数据
  let isConsistent =
    selections.value.every(
      (item) => item.productionPlanNo === selections.value[0].productionPlanNo
    ) &&
    selections.value.every(
      (item) => item.processAlias === selections.value[0].processAlias
    );

  if (!isConsistent) {
    proxy.$modal.msgError("请选择相同计划单且当前工序相同的数据");
    return;
  }

  //判断是否未修改过的批次
  isConsistent =
    selections.value.every((item) => item.isAmend == 0) &&
    selections.value.every((item) => item.isWaste == 0) &&
    selections.value.every((item) => item.isWasteRecycling == 0);

  if (!isConsistent) {
    proxy.$modal.msgError("多批单改只能修改未修改过的批次");
    return;
  }
  proxy.$refs.multiChangeRef.open(selections);
}

/** 打开批次详情页 */
function handleColumnClick(lotCode) {
  router.push({ path: "/reviseBath/lotFormParticulars/" + lotCode });
}

/** 单批单改按钮操作 */
function handleOnceSingleChange() {
  if (selections.value[0].isWaste == 1) {
    proxy.$message.error("批废不能再进行操作");
    return;
  }

  proxy.$refs.onceChangeRef.open(selections.value[0].lotCode);
}

/**获取生产计划列表 */
function getLot() {
  const lotQueryParams = lotStore().lotQueryParams;
  console.log("getLot", lotQueryParams);

  if (lotQueryParams != null) {
    queryParams.value = lotQueryParams;
  }

  loading.value = true;
  getLotList(queryParams.value).then((res) => {
    if (res.code == 200) {
      console.log(res);
      lotList.value = res.rows;
      total.value = res.total;
      loading.value = false;
    }
  });
}

function getNowDate() {
  // var nowDate = new Date();
  // var date = {
  //   year: nowDate.getFullYear(),
  //   month: nowDate.getMonth() + 1,
  //   day: nowDate.getDate(),
  // };
  // const dayDate =
  //   date.year +
  //   "-" +
  //   (date.month >= 10 ? date.month : "0" + date.month) +
  //   "-" +
  //   (date.day >= 10 ? date.day : "0" + date.day);
  // console.log(dayDate);
  queryParams.value.endTime = proxy.moment().format("YYYY-MM-DD");
}

function getPassDate() {
  // var myDate = new Date();
  // myDate.setDate(myDate.getDate() - 29);
  // var dateTemp;
  // var day;
  // for (var i = 0; i < 30; i++) {
  //   if (myDate.getDate() < 10) {
  //     day = "0" + myDate.getDate().toString();
  //   } else {

  //     day = myDate.getDate().toString();
  //   }
  // }
  // var month = myDate.getMonth() + 1;
  // dateTemp =
  //   myDate.getFullYear() +
  //   "-" +
  //   (month < 10 ? "0" + month : "" + month) +
  //   "-" +
  //   day;
  queryParams.value.startTime = proxy
    .moment()
    .subtract(3, "month")
    .format("YYYY-MM-DD");
}

/**搜索 */
function handleQuerydaywork() {
  queryParams.value.lineNumber = null;
  // if (queryParams.value.flags.some((item) => item == '1')) {
  //   queryParams.value.isAmend = 1
  // } else {
  //   queryParams.value.isAmend = null
  // }
  // if (queryParams.value.flags.some((item) => item == '2')) {
  //   queryParams.value.isWasteRecycling = 1
  // } else {
  //   queryParams.value.isWasteRecycling = null
  // }

  // if (queryParams.value.flags.some((item) => item == '0')) {
  //   queryParams.value.isWaste = 1
  // } else {
  //   queryParams.value.isWaste = null
  // }
  const query = queryParams.value;
  if (
    queryParams.value.endTime < queryParams.value.startTime &&
    queryParams.value.endTime != "" &&
    queryParams.value.startTime != ""
  ) {
    proxy.$modal.msgError("结束时间不能小于开始时间");
  } else {
    if (query.productDescription) {
      queryParams.value.productDescription = query.productDescription.trim();
    }

    if (query.lotCode) {
      queryParams.value.lotCode = query.lotCode.trim();
    }

    if (query.productionPlanNo) {
      queryParams.value.productionPlanNo = query.productionPlanNo.trim();
    }

    const lotQueryParams = JSON.parse(JSON.stringify(queryParams.value));
    console.log("lotQueryParams", lotQueryParams);
    lotStore().setlotQueryParams(lotQueryParams);
    getLot();
  }
}
/**打开废品回用弹窗 */
function handleWasteRecycling() {
  proxy.$refs.wasteRecyclingDialogRef.open(selections.value);
}
/**
 * 对话框关闭 事件
 */
function close() {
  visible.value = false;
}

/**搜索栏清空 */
function reset() {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    lotCode: "",
    deptId: null,
    isFallback: "",
    isWasteRecycling: "",
  };
  proxy.resetForm("queryRef");
}
function handleSelectionChange(selection) {
  selections.value = selection;
  once.value = selections.value.length == 1 ? false : true;
  multi.value = selections.value.length > 1 ? false : true;
}

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

const showInBatch = () => {
  if (selections.value[0].isWaste == 1) {
    proxy.$message.error("批废不能再进行操作");
    return;
  }

  inBatchesDialogRef.value.open(selections.value[0]);
};

/** 获取工序列表 */
const queryProcessSearchAsync = (arg, cb) => {
  const params =
    arg != null
      ? { processAlias: arg, ...queryParams.value }
      : { ...queryParams.value };
  // listProcess(params).then(res => {
  //   const processes = res.rows
  //   cb(processes)
  // })
  getProcessList(params)
    .then((response) => {
      const processes = response.data;
      cb(processes);
    })
    .catch((err) => {
      // console.log(err)
    });
};

const handleProcessSelect = (item) => {
  console.log(item);
  processAlias.value = item.label.trim();
  queryParams.value.processId = item.value;
  queryParams.value.processAlias = processAlias.value;
};

const queryDeptSearchAsync = (arg, cb) => {
  const params =
    arg != null
      ? { pageSize: 200, deptName: arg, isWorkSection: 1 }
      : { pageSize: 200 };
  listDept(params).then((res) => {
    const depts = res.rows;
    cb(depts);
  });
};

const handleDeptSelect = (item) => {
  console.log(item);
  deptName.value = item.deptName.trim();
  queryParams.value.deptName = deptName.value;
  queryParams.value.deptId = item.deptId;
};
const handleClearProcess = () => {
  processAlias.value = "";
  queryParams.value.processId = null;
};
const handleClearDept = () => {
  deptName.value = "";
  queryParams.value.deptId = null;
};
const handleFlagChange = (selection) => {
  console.log(selection);
};
const checkRecycle = () => {
  // 判断是否是废品回用，废品回用的无论分批还是单批单改多批单改废品回用都不能做
  return selections.value.some((v) => v.isWasteRecycling == 1);
};

onMounted(() => {
  getDept();
  // getLot();
});
</script>