<template>
  <el-dialog title="周转申请" v-model="visible" width="400px" append-to-body draggable :close-on-click-modal="false"
    v-loading="loading">
    <div class="mb-2 ml-4" style="margin-top: 10px; margin-bottom: 10px">
      <el-radio-group v-model="turnoverType" @change="typeChange" size="large">
        <el-radio-button v-for="item in turnoverTypeList" :key="item.dictValue" :label="item.dictValue">
          {{ item.dictLabel }}
        </el-radio-button>
      </el-radio-group>
    </div>

    <div class="form-container">
      <el-form ref="deptRef" class="master-container" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="下序工段:" v-if="turnoverType && turnoverType != 3" prop="lotCode">
          <el-select v-if="turnoverType == 1" v-model="curDayworkItem.deptId" remote reserve-keyword
            style="width: 200px" placeholder="请选择下序工段" value-key="value" :loading="loadingCarrier"
            @change="(arg) => handleChangeInside(arg)">
            <el-option v-for="item in insideDepts" :key="item.value" :label="item.text" :value="item.value" />
          </el-select>

          <el-select v-if="turnoverType == 2" v-model="curDayworkItem.deptId" remote reserve-keyword
            style="width: 200px" placeholder="请选择下序工段" value-key="value" :loading="loadingCarrier"
            @change="(arg) => handleChangeInside(arg)">
            <el-option v-for="item in outsideDepts" :key="item.value" :label="item.text" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="turnoverType && (turnoverType == 2 || turnoverType == 1)" label="是否包装签票："
          prop="isSortPackaging" label-width="130px">
          <el-switch v-model="curDayworkItem.isSortPackaging" active-text="是" :active-value="1" inactive-text="否"
            :inactive-value="0" />
        </el-form-item>
        <el-form-item label="摆放位置:" v-if="curDayworkItem.deptId" prop="lotCode">
          <el-select v-if="turnoverType == 1" v-model="curDayworkItem.turnAreaList" multiple remote reserve-keyword
            style="width: 200px" placeholder="请选择摆放位置" value-key="id" :loading="loadingCarrier"
            @change="(arg) => handleTurnAreaChange(arg)">
            <el-option v-for="item in turnAreaList" :key="item.id" :label="item.code" :value="item" />
          </el-select>
          <el-select v-if="turnoverType == 2" v-model="curDayworkItem.turnAreaList" remote reserve-keyword
            style="width: 200px" placeholder="请选择摆放位置" value-key="id" :loading="loadingCarrier"
            @change="(arg) => handleTurnAreaChange(arg)">
            <el-option v-for="item in turnoverArea" :key="item.id" :label="item.code" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="摆放位置:" v-if="turnoverType == 3" prop="lotCode">
          <el-select v-model="curDayworkItem.turnAreaList" remote reserve-keyword style="width: 200px"
            placeholder="请选择摆放位置" value-key="id" :loading="loadingCarrier" @change="(arg) => handleTurnAreaChange(arg)">
            <el-option v-for="item in turnoverArea" :key="item.id" :label="item.code" :value="item" />
          </el-select>
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <el-button type="primary" icon="Check" @click="handleSave">保存</el-button>
      <el-button icon="Close" @click="handleCancel">取 消</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref } from "vue";
import {
  getTurnoverListByDeptId,
  getDictInfoByType,
  getTurnoverByWorkshop,
  getDayWorkItemList,
  getDeptList,
  turnover,
  turnoverOutsource,
} from "@/api/business/specialDaywork";
import useUserStore from "@/store/modules/user";
const props = defineProps({
  getList: {
    type: Function,
    default: () => { },
  },
});

const { getList } = toRefs(props);
const { proxy } = getCurrentInstance();

/** 字典数组区 */

const loading = ref(false);
const turnoverInfoType = ref(true);
const turnAreaList = ref([]); //摆放位置集合
const deptList = ref([]); // 工段列表
const insideDepts = ref([]); // 车间内工段
const outsideDepts = ref([]); // 车间外工段
// const outTurnArea = ref([]);
const turnoverTypeList = ref([]);
const turnoverArea = ref([]); //车间外周摆放位置
const visible = ref(false);
const selection = ref([]);
const turnoverType = ref(null);
const dayworkList = ref([]);
const daywork = ref({});
const curDayworkItemList = ref([]);
const curDayworkItem = ref({});

/** 查询对象 */
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
});

/***********************  方法区  ****************************/
/** 打开抽屉 */
const open = (rows) => {
  reset();
  console.log("open", rows);
  daywork.value = rows[0];
  dayworkList.value = rows;
  console.log("daywork", daywork.value);
  visible.value = true;
  init();
};

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

/** 周转类型切换操作 */
function typeChange(value) {
  turnAreaList.value = [];
  turnAreaList.value = [];
  curDayworkItem.value = {};
}

function handleChangeInside(reg) {
  let deptInfo = {}
  deptInfo = insideDepts.value.find(item => item.value == reg)
  if (deptInfo == null) {
    deptInfo = outsideDepts.value.find(item => item.value == reg)
  }
  if (deptInfo.data.isSortPackaging == 1) {
    curDayworkItem.value.isSortPackaging = 1
  } else {
    curDayworkItem.value.isSortPackaging = 0
  }
  console.log("deptInfo", deptInfo)
  turnAreaList.value = [];
  selection.value = [];
  getTurnoverListByDeptId({
    deptId: reg,
  }).then((res) => {
    for (var i = 0; i < res.data.length; i++) {
      if (res.data[i].status != 1) {
        turnAreaList.value[i] = res.data[i];
      }
    }
  });
}

/** 摆放选择 */
function handleTurnAreaChange(reg) {
  console.log("reg", reg);
}

/** 表单重置 */
function reset() {
  insideDepts.value = [];
  turnAreaList.value = [];
  deptList.value = [];
  insideDepts.value = [];
  outsideDepts.value = [];
  daywork.value = {};
  dayworkList.value = [];
  turnoverType.value = null;
  curDayworkItem.value = {};
}

/** 提交按钮 */
function handleSave() {
  if (!curDayworkItem.value.turnAreaList) {
    proxy.$modal.msgError("请选择完成周转信息");
    return;
  }
  curDayworkItem.value.turnoverType = turnoverType.value;

  if (turnoverType.value == "3") {
    handleConfirmOutsource();
  } else {
    curDayworkItem.value.id = null;
    curDayworkItem.value.status = "4";
    (curDayworkItem.value.startTime = proxy.parseTime(
      new Date(),
      "{y}-{m}-{d} {h}:{i}:{s}"
    )),
      (curDayworkItem.value.endTime = proxy.parseTime(
        new Date(),
        "{y}-{m}-{d} {h}:{i}:{s}"
      )),
      (curDayworkItem.value.technologicalProcessId =
        daywork.value.technologicalProcessId);

    if (curDayworkItem.value.turnoverType == 1) {
      // 过滤出周转位置的数组,并转换成字符串
      const newArray = curDayworkItem.value.turnAreaList.map((item) => {
        if (item.code) {
          return item.code;
        } else if (item.dictLabel) {
          return item.dictLabel;
        } else {
          return null;
        }
      });
      const newIdArray = curDayworkItem.value.turnAreaList.map((item) => {
        if (item.id) {
          return item.id;
        } else {
          return null;
        }
      });

      curDayworkItem.value.place = newArray.join("、");
      //0628将位置id也拼接的方式存下来
      curDayworkItem.value.placeId = newIdArray.join("、");
      curDayworkItem.value.turnoverArea = "车间内周转看place字段";
    } else {
      curDayworkItem.value.turnoverArea =
        curDayworkItem.value.turnAreaList.code;
      //0628将位置id也拼接的方式存下来
      curDayworkItem.value.turnoverId = curDayworkItem.value.turnAreaList.id;
    }

    //设置周转下一个车间名
    for (let i = 0; i < deptList.value.length; i++) {
      if (deptList.value[i].deptId == curDayworkItem.value.deptId) {
        curDayworkItem.value.deptName = deptList.value[i].deptName;
      }
    }
    // 遍历curDayworkItemList，并对每一项指定字段赋值
    curDayworkItemList.value = curDayworkItemList.value.map((item) => {
      return {
        ...item, // 保留原始item的所有属性
        id: null, // 指定字段赋值
        status: curDayworkItem.value.status, // 指定字段赋值
        startTime: curDayworkItem.value.startTime, // 指定字段赋值
        endTime: curDayworkItem.value.endTime, // 指定字段赋值
        deptId: curDayworkItem.value.deptId,
        workingHours: 0,
        technologicalProcessId: curDayworkItem.value.technologicalProcessId, // 指定字段赋值
        deptName: curDayworkItem.value.deptName,
        place: curDayworkItem.value.place ? curDayworkItem.value.place : null,
        placeId: curDayworkItem.value.placeId,
        createTime: null,
        updateTime: null,
        turnoverArea: curDayworkItem.value.turnoverArea,
        turnoverType: curDayworkItem.value.turnoverType,
        turnoverId: curDayworkItem.value.turnoverId,
        isSortPackaging: curDayworkItem.value.isSortPackaging
      };
    });
    console.log(curDayworkItemList.value)
    turnoverSave();
  }
}

/** 周转保存请求 */
function turnoverSave() {
  turnover(curDayworkItemList.value).then((res) => {
    if (res.code === 200) {
      proxy.$modal.msgSuccess("保存成功！");
      visible.value = false;
      reset();
      getList.value();
    } else {
      proxy.$modal.msgError("保存失败！");
    }
  });
}

function handleConfirmOutsource() {
  curDayworkItem.value.id = null;
  curDayworkItem.value.status = "4";
  (curDayworkItem.value.startTime = proxy.parseTime(
    new Date(),
    "{y}-{m}-{d} {h}:{i}:{s}"
  )),
    (curDayworkItem.value.endTime = proxy.parseTime(
      new Date(),
      "{y}-{m}-{d} {h}:{i}:{s}"
    )),
    (curDayworkItem.value.technologicalProcessId =
      daywork.value.technologicalProcessId);
  curDayworkItem.value.turnoverArea = curDayworkItem.value.turnAreaList.code;
  curDayworkItem.value.turnoverId = curDayworkItem.value.turnAreaList.id;

  // 遍历curDayworkItemList，并对每一项指定字段赋值
  curDayworkItem.value.deptCode = 170000;

  curDayworkItemList.value = curDayworkItemList.value.map((item) => {
    return {
      ...item, // 保留原始item的所有属性
      id: null, // 指定字段赋值
      status: curDayworkItem.value.status, // 指定字段赋值
      startTime: curDayworkItem.value.startTime, // 指定字段赋值
      endTime: curDayworkItem.value.endTime, // 指定字段赋值
      technologicalProcessId: curDayworkItem.value.technologicalProcessId, // 指定字段赋值
      deptName: curDayworkItem.value.deptName,
      place: curDayworkItem.value.place ? curDayworkItem.value.place : null,
      turnoverArea: curDayworkItem.value.turnoverArea,
      turnoverType: curDayworkItem.value.turnoverType,
      turnoverId: curDayworkItem.value.turnoverId,
      deptCode: 170000,
      isSortPackaging: curDayworkItem.value.isSortPackaging
    };
  });
  /**** 此处暂时为硬编码，170000为外协部门编码，根据编码查询信息 ***/
  turnoverOutsource(curDayworkItemList.value).then((res) => {
    if (res.code === 200) {
      proxy.$modal.msgSuccess("保存成功！");
      visible.value = false;
      reset();
      getList.value();
    } else {
      proxy.$modal.msgError("保存失败！");
    }
  });
}

function init() {
  getDictInfoByType("daywork_turnover_type").then((res) => {
    turnoverTypeList.value = res.data;
    getTurnoverByWorkshop({
      deptId: daywork.value.deptId,
    }).then((res) => {
      turnoverArea.value = res.data;
      getDeptList({
        tenantId: useUserStore().user.tenantId,
        productionPlanDetailId: daywork.value.productionPlanDetailId,
        lotId: daywork.value.lotId,
        isWasteRecycling: daywork.value.isWasteRecycling,
        isAmend: daywork.value.isAmend,
      }).then((res) => {
        for (let i = 0; i < res.data.length; i++) {
          deptList.value = res.data;
          if (turnoverArea.value[0].workshopId == res.data[i].workshopId) {
            insideDepts.value.push({
              text: res.data[i].deptName,
              value: res.data[i].deptId,
              data: res.data[i],
            });
          } else {
            outsideDepts.value.push({
              text: res.data[i].deptName,
              value: res.data[i].deptId,
              data: res.data[i],
            });
          }
        }
      });
    });
  });

  getDayWorkItemList(dayworkList.value).then((res) => {
    if (res.code == 200) {
      curDayworkItemList.value = res.data;
    }
  });
}

/** 暴露给父组件的方法 */
defineExpose({
  open,
});
</script>
<style scoped>
.switch-container {
  font-size: 15px;
  margin-left: 10px;
  display: flex;
  align-items: center;
  justify-content: left;
}

.ml-15 {
  margin-left: 15px;
  margin-right: 15px;
}
</style>
