<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100px">
            <el-form-item label="入库名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入入库名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="入库单号" prop="sn">
              <el-input v-model="queryParams.sn" placeholder="请输入入库单号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery"> 搜索 </el-button>
              <el-button icon="Refresh" @click="resetQuery"> 重置 </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"> 新增 </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList" />
        </el-row>
      </template>

      <el-table v-loading="loading" :data="tableList" >
        <el-table-column label="入库单号" align="center" show-overflow-tooltip prop="sn" width="180" />
        <el-table-column label="入库名称" align="center" show-overflow-tooltip prop="name" width="150" />
        <el-table-column label="设备种类" align="center" show-overflow-tooltip prop="deviceCategory" width="150" />
        <el-table-column label="到货数量" align="center" show-overflow-tooltip prop="deviceNum" width="150" />
        <el-table-column label="入库仓库" align="center" show-overflow-tooltip  width="150" >
          <template #default="scope">
            <span>{{ formatWareHouse(scope.row.warehouseId) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="入库人" align="center" show-overflow-tooltip prop="createName" width="150" />
        <el-table-column label="入库时间" align="center" show-overflow-tooltip prop="createTime" width="150" />
        <el-table-column label="入库说明" align="center" show-overflow-tooltip prop="remark" width="150" />
        <!-- <el-table-column label="操作" align="center" width="100" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button size="small" link type="primary" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button size="small" link type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column> -->
      </el-table>
      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
        :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="1200px" append-to-body>
      <el-form ref="addFormRef" :model="form" label-width="110px">
        <SubTitle title="基本信息" />
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入库单号" prop="sn">
              <el-input v-model="form.sn" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库名称" prop="name" :rules="[{ required: true, message: '入库名称不能为空', trigger: 'blur' }]">
              <el-input v-model="form.name" placeholder="请输入入库名称" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="入库人" prop="createName">
              <el-input v-model="form.createName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库仓库" prop="warehouseId"
              :rules="[{ required: true, message: '入库仓库不能为空', trigger: 'change' }]">
              <el-select v-model="form.warehouseId" clearable placeholder="请选择入库仓库" @change="getShelfList">
                <el-option v-for="item in wareHouseOptions" :key="item.id" :value="item.id"
                  :label="item.name"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库时间" prop="ext1.storeDate"
              :rules="[{ required: true, message: '入库时间不能为空', trigger: 'change' }]">
              <el-date-picker v-model="form.ext1.storeDate" style="width: 100%;" value-format="YYYY-MM-DD" type="date"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="到货入库说明" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <div class="device-title">
          <SubTitle title="采购备品备件" style="margin-bottom: 10px;" />
          <div>
            <span>设备种类：{{ deviceTypeNum }}</span>
            <span>合计入库数量：{{ deviceNum }}</span>
          </div>
        </div>

        <el-table :data="form.deviceInfo" max-height="300">
          <el-table-column label="备品备件名称" align="center" width="120">
            <template #default="scope">
              <el-select v-model="scope.row.deviceTypeDetailId" clearable placeholder="请选择"
                @change="devTypeDetailChange($event, scope.$index)">
                <el-option v-for="dict in deviceTypeDetailOptions" :key="dict.id" :label="dict.deviceType.name"
                  :value="dict.id">
                  <span style="float: left">{{ dict.deviceType.name }}</span>
                  <span style="float: right;color: var(--el-text-color-secondary);font-size: 13px;">
                    {{ dict.ext1.brand }}{{ dict.xh }}
                  </span>
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="品牌" align="center" width="130">
            <template #default="scope">
              <el-input v-model="scope.row.brand" disabled />
            </template>
          </el-table-column>
          <el-table-column label="型号" align="center" width="120">
            <template #default="scope">
              <el-input v-model="scope.row.xh" disabled />
            </template>
          </el-table-column>
          <el-table-column label="供应商" align="center" width="120">
            <template #default="scope">
              <el-input v-model="scope.row.productor" disabled />
            </template>
          </el-table-column>
          <el-table-column label="单位" align="center" width="80">
            <template #default="scope">
              <el-input v-model="scope.row.unit" disabled />
            </template>
          </el-table-column>
          <el-table-column label="质保期" align="center" width="150">
            <template #default="scope">
              <el-date-picker v-model="scope.row.qualityEndTime" style="width: 100%;" value-format="YYYY-MM-DD"
                type="date" placeholder="选择日期">
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="本次入库数量" align="center">
            <template #default="scope">
              <el-input-number v-model="scope.row.num" style="width: 100%;" :min="1" controls-position="right" />
            </template>
          </el-table-column>
          <el-table-column label="入库库位" align="center">
            <template #default="scope">
              <el-select v-model="scope.row.shelfInfo" clearable placeholder="请选择">
                <el-option v-for="dict in shelfOptions" :key="dict.shelfName" :label="dict.shelfName"
                  :value="dict.shelfName">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="80" fixed="right">
            <template #header>
              <div class="operateBtn">
                <span>操作</span>
                <el-icon @click="addDeviceInfo">
                  <CirclePlus />
                </el-icon>
              </div>
            </template>
            <template #default="scope">
              <el-icon @click="delDeviceInfo(scope.$index)">
                <Delete />
              </el-icon>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm"> 确 定 </el-button>
          <el-button @click="cancel"> 取 消 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="InStore" lang="ts">
import { deepClone } from '@/utils';
import useUserStore from '@/store/modules/user';
import { listWarehouse, listDeviceInWarehouse, addDeviceInWarehouse } from '@/api/sparesManage/index';
import { listDeviceType, getDeviceTypeDetailList } from '@/api/deviceManage/deviceType';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const tableList = ref([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const queryFormRef = ref<ElFormInstance>();
const addFormRef = ref<ElFormInstance>();
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const initFormData = {
  id: undefined,
  sn: undefined,
  name: undefined,
  warehouseId: undefined,
  createName: undefined,
  remark: undefined,
  deviceInfo: [{
    deviceTypeDetailId: '',
    brand: '',
    xh: '',
    productor: '',
    qualityEndTime: '',
    unit: '',
    num: '',
    shelfInfo: ''
  }],
  ext1: {
    storeDate: undefined,
  },
  ext2: undefined
};
const formData = reactive({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 100000,
    name: undefined,
    sn: undefined,
    params: {}
  }
});
const { queryParams, form } = toRefs(formData);
const deviceTypeDetailOptions = ref([])
const wareHouseOptions = ref([])
const shelfOptions = ref([])

const deviceTypeNum = computed(() => {
  const { deviceInfo } = form.value
  return uniqueByField(deviceInfo.filter(item => item.deviceTypeDetailId != ''), 'deviceTypeDetailId').length
});
const formatWareHouse = (val) => {
  return wareHouseOptions.value.filter(item => item.id === val)[0]?.name
}
const deviceNum = computed(() => {
  const { deviceInfo } = form.value
  return deviceInfo.filter(item => item.num !== '').reduce((total, item) => total + Number(item.num), 0)
});
const uniqueByField = (arr, field) => {
  const set = new Set();
  arr.forEach(item => {
    set.add(item[field]);
  });
  return Array.from(set);
}
/** 查询列表 */
const getList = async () => {
  loading.value = true;
  const res = await listDeviceInWarehouse(queryParams.value);
  const tmpObj = {}
  res.rows.forEach(item => {
    if (tmpObj[item.sn]) {
      tmpObj[item.sn].push(item)
    } else {
      tmpObj[item.sn] = [item]
    }
  })
  const tmpArr =[]
  Object.keys(tmpObj).forEach(key => {
    if (tmpObj[key].length) {
      tmpArr.push({
        deviceCategory:tmpObj[key].length,
        deviceNum: tmpObj[key].reduce((total, item) => total + Number(item.num), 0),
        ...tmpObj[key][0],
      })
    }

  })
  tableList.value = tmpArr
  total.value = tmpArr.length;
  loading.value = false;
};

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

/** 表单重置 */
const reset = () => {
  form.value = { ...deepClone(initFormData) };
  addFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  form.value.sn = generateSerialNumber()
  form.value.createName = useUserStore().nickname
  dialog.visible = true;
  dialog.title = '新增到货入库';
};
/** 修改按钮操作 */
const handleUpdate = (row) => {
  reset();
  Object.assign(form.value, row)
  dialog.visible = true;
  dialog.title = '修改到货入库';
};

/** 提交按钮 */
const submitForm = () => {
  addFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      const { deviceInfo, ext1, ...rest } = form.value
      if (deviceInfo.length === 0) return proxy?.$modal.msgError('请填写备品备件信息')
      const validFlag = deviceInfo.some(item => !item.deviceTypeDetailId || !item.qualityEndTime  || !item.num || !item.shelfInfo)
      if (validFlag) return proxy?.$modal.msgError('请填写完善备品备件信息')
      buttonLoading.value = true;
      deviceInfo.forEach(async (item, index) => {
        const params = {
          ...rest,
          ext1: JSON.stringify(ext1),
          deviceTypeDetailId: item.deviceTypeDetailId,
          qualityEndTime: item.qualityEndTime,
          num: item.num,
          shelfInfo: item.shelfInfo,
        }
        await addDeviceInWarehouse(params);
        if (index === deviceInfo.length - 1) {
          proxy?.$modal.msgSuccess('操作成功');
          buttonLoading.value = false;
          dialog.visible = false;
          getList();
        }
      })

    }
  });
};
/**
 * @name  getTableData
 * @desc  纯JS前端分页方法
 * @param  {Number} page 当前页码，默认1
 * @param  {Number} pageSize 每页最多显示条数，默认10
 * @param  {Array} totalData 总的数据集，默认为空数组
 * @return {Object} {
    data, //当前页展示数据，数组
    page, //当前页码
    pageSize, //每页最多显示条数
    length, //总的数据条数
  }
**/
const getTableData = (page = 1, pageSize = 10, totalData = []) => {
  const { length } = totalData;
  const tableData = {
    data: [],
    page,
    pageSize,
    length,
  };
  if (pageSize >= length) { //pageSize大于等于总数据长度，说明只有1页数据或没有数据
    tableData.data = totalData;
    tableData.page = 1;//直接取第一页
  } else { //pageSize小于总数据长度，数据多余1页
    const num = pageSize * (page - 1);//计算当前页（不含）之前的所有数据总条数
    if (num < length) { //如果当前页之前所有数据总条数小于（不能等于）总的数据集长度，则说明当前页码没有超出最大页码
      const startIndex = num;//当前页第一条数据在总数据集中的索引
      const endIndex = num + pageSize - 1;//当前页最后一条数据索引
      tableData.data = totalData.filter((_, index) => index >= startIndex && index <= endIndex);//当前页数据条数小于每页最大条数时，也按最大条数范围筛取数据
    } else { //当前页码超出最大页码，则计算实际最后一页的page，自动返回最后一页数据
      const size = parseInt((length / pageSize).toString()); //取商
      const rest = length % pageSize; //取余数
      if (rest > 0) { //余数大于0，说明实际最后一页数据不足pageSize，应该取size+1为最后一条的页码
        tableData.page = size + 1;//当前页码重置，取size+1
        tableData.data = totalData.filter((_, index) => index >= (pageSize * size) && index <= length);
      } else if (rest === 0) { //余数等于0，最后一页数据条数正好是pageSize
        tableData.page = size;//当前页码重置，取size
        tableData.data = totalData.filter((_, index) => index >= (pageSize * (size - 1)) && index <= length);
      } //注：余数不可能小于0
    }
  }
  return tableData;
};
/** 删除按钮操作 */
const handleDelete = async (row) => {
  // const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除？').finally(() => (loading.value = false));
  // await delInspectionTask(_ids);
  // proxy?.$modal.msgSuccess('删除成功');
  // await getList();
};
const addDeviceInfo = () => {
  form.value.deviceInfo.push({
    deviceTypeDetailId: '',
    brand: '',
    xh: '',
    productor: '',
    qualityEndTime: '',
    unit: '',
    num: '',
    shelfInfo: ''
  })
}
const delDeviceInfo = (index) => {
  form.value.deviceInfo.splice(index, 1)
}
const getWarehouseList = () => {
  listWarehouse({}).then(({ code, rows }) => {
    if (code === 200) {
      wareHouseOptions.value = rows
    }
  })
}
const getShelfList = (val) => {
  if (val) {
    const [{ shelfs }] = wareHouseOptions.value.filter(item => item.id === val)
    shelfOptions.value = JSON.parse(shelfs).shelfsData
  } else {
    shelfOptions.value = []
  }
}
const generateSerialNumber = () => {
  const date = new Date();
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  const seconds = date.getSeconds().toString().padStart(2, '0');
  const milliseconds = date.getMilliseconds().toString().padStart(3, '0');
  return `${year}${month}${day}${hours}${minutes}${seconds}${milliseconds}`;
}
const getDeviceTypeList = async () => {
  let deviceTypeList = []
  await listDeviceType({}).then(({ code, rows }) => {
    if (code === 200) {
      deviceTypeList = rows || []
    }
  })
  let deviceTypeDetailList = []
  await getDeviceTypeDetailList({}).then(({ code, rows }) => {
    if (code === 200) {
      deviceTypeDetailList = rows.map((item) => ({
        ...item,
        deviceType: {},
        ext1: item.ext1 ? JSON.parse(item.ext1) : null
      }));
    }
  });
  deviceTypeDetailList.forEach(item => {
    deviceTypeList.forEach(el => {
      if (item.deviceTypeId === el.id) {
        item.deviceType = el
      }
    })
  })
  deviceTypeDetailOptions.value = deviceTypeDetailList
};
const devTypeDetailChange = (val, index) => {
  if (val) {
    const [{ ext1: { brand, productorName }, xh,units }] = deviceTypeDetailOptions.value.filter(item => item.id === val)
    form.value.deviceInfo[index].brand = brand
    form.value.deviceInfo[index].xh = xh
    form.value.deviceInfo[index].productor = productorName
    form.value.deviceInfo[index].unit = units
  }

}

onMounted(() => {
  getList();
  getWarehouseList()
  getDeviceTypeList()
});
</script>
<style lang="scss" scoped>
.operateBtn {
  display: flex;
  align-items: center;

  .el-icon {
    color: #409eff;
    margin-left: 5px;
    cursor: pointer;
  }
}

.device-title {
  display: flex;
  justify-content: space-between;
  align-items: center;

  >div:last-child {
    color: #01A7F0;

    span:last-child {
      margin-left: 40px;
    }
  }
}
</style>
