<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>
              <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">
          <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="name" width="150" />
        <el-table-column label="品牌" align="center" show-overflow-tooltip prop="ext1.brand" width="150" />
        <el-table-column label="型号" align="center" show-overflow-tooltip prop="xh" width="150" />
        <el-table-column label="供应商" align="center" show-overflow-tooltip prop="ext1.productorName" width="150" />
        <el-table-column label="安全库存数量" align="center" show-overflow-tooltip prop="safe_num" width="150" />
        <el-table-column label="单位" align="center" show-overflow-tooltip prop="units" width="150" />
        <el-table-column label="用途" align="center" show-overflow-tooltip prop="remark" width="150" />
        <el-table-column label="实时库存" align="center" show-overflow-tooltip prop="current_stock" width="150">
          <template #default="{ row }">
            <span :style="{ 'color': row.current_stock < row.safe_num ? 'red' : null }">{{ row.current_stock }}</span>
          </template>
        </el-table-column>
        <el-table-column label="是否有过期备件" align="center" show-overflow-tooltip prop="has_expired" width="150">
          <template #default="{ row }">
            <el-tag v-if="row.has_expired == '是'" type="danger">是</el-tag>
            <el-tag v-else>否</el-tag>
          </template>
        </el-table-column>
        <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="handleDetail(scope.row)">详情</el-button>
            <el-button size="small" link type="danger" @click="handleRemove(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="1100px" append-to-body>
      <el-form ref="addFormRef" :model="form" label-width="110px">
        <SubTitle title="备品信息" />
        <div class="drawer-title">
          <el-descriptions title="" direction="vertical" :column="7">
            <el-descriptions-item align="center" label="备品备件名称">{{ curRow.name }}</el-descriptions-item>
            <el-descriptions-item align="center" label="品牌">{{ curRow.ext1.brand }}</el-descriptions-item>
            <el-descriptions-item align="center" label="型号">{{ curRow.xh }}</el-descriptions-item>
            <el-descriptions-item align="center" label="供应商">{{ curRow.ext1.productorName }}</el-descriptions-item>
            <el-descriptions-item align="center" label="安全库存数量">{{ curRow.safe_num }}</el-descriptions-item>
            <el-descriptions-item align="center" label="单位">{{ curRow.units }}</el-descriptions-item>
            <el-descriptions-item align="center" label="实时库存">{{ curRow.current_stock }}</el-descriptions-item>
          </el-descriptions>
        </div>
        <SubTitle title="出库信息" style="margin-top: 20px;" />
        <el-row style="margin-top: 10px;">
          <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="ext1.removeDate"
              :rules="[{ required: true, message: '出库时间不能为空', trigger: 'change' }]">
              <el-date-picker v-model="form.ext1.removeDate" 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="recipientsId"
              :rules="[{ required: true, message: '领用人不能为空', trigger: 'change' }]">
              <el-select v-model="form.recipientsId" clearable placeholder="请选择领用人">
                <el-option v-for="item in userOptions" :key="item.userId" :label="item.nickName"
                  :value="item.userId"></el-option>
              </el-select>
            </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>
        <SubTitle title="备品备件出库" style="margin-top: 20px;" />
        <el-table :data="curRow.inWarehouseList" max-height="300">
          <el-table-column label="入库单号" align="center" prop="sn" show-overflow-tooltip width="150">
          </el-table-column>
          <el-table-column label="入库名称" align="center" prop="name">
          </el-table-column>
          <el-table-column label="入库数量" align="center" prop="num">
          </el-table-column>
          <el-table-column label="入库时间" align="center" show-overflow-tooltip prop="ext1.storeDate"></el-table-column>
          <el-table-column label="实时库存" align="center" show-overflow-tooltip prop="current_stock"></el-table-column>
          <el-table-column label="在库时长(天)" align="center" show-overflow-tooltip
            prop="in_warehouse_days"></el-table-column>
          <el-table-column label="剩余寿命(天)" align="center" show-overflow-tooltip
            prop="remaining_life_days"></el-table-column>
          <el-table-column label="寿命超期(天)" align="center" show-overflow-tooltip
            prop="life_exceeded_days"></el-table-column>
          <el-table-column label="出库数量" align="center">
            <template #default="{ row }">
              <el-input-number v-model="row.removeNum" style="width: 100%;" :min="0" :max="row.current_stock"
                controls-position="right" />
            </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>
    <el-drawer v-model="detailDrawer" class="customDrawer" size="70%">
      <template #header>
        <div class="drawer-title">
          <div class="title-name">备品备件详情</div>
          <el-descriptions title="" direction="vertical" :column="7">
            <el-descriptions-item align="center" label="备品备件名称">{{ curRow.name }}</el-descriptions-item>
            <el-descriptions-item align="center" label="品牌">{{ curRow.ext1.brand }}</el-descriptions-item>
            <el-descriptions-item align="center" label="型号">{{ curRow.xh }}</el-descriptions-item>
            <el-descriptions-item align="center" label="供应商">{{ curRow.ext1.productorName }}</el-descriptions-item>
            <el-descriptions-item align="center" label="安全库存数量">{{ curRow.safe_num }}</el-descriptions-item>
            <el-descriptions-item align="center" label="单位">{{ curRow.units }}</el-descriptions-item>
            <el-descriptions-item align="center" label="实时库存">{{ curRow.current_stock }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </template>
      <div>
        <el-tabs v-model="detailTab">
          <el-tab-pane label="基础信息" name="1">
            <el-descriptions class="detail-descriptions" :column="2" border>
              <el-descriptions-item label-align="center" label="备品备件名称">{{ curRow.name }}</el-descriptions-item>
              <el-descriptions-item label-align="center" label="备品备件编号">{{ curRow.id }}</el-descriptions-item>
              <el-descriptions-item label-align="center" label="品牌">{{ curRow.ext1.brand }}</el-descriptions-item>
              <el-descriptions-item label-align="center" label="型号">{{ curRow.xh }}</el-descriptions-item>
              <el-descriptions-item label-align="center" label="供应商">{{ curRow.ext1.productorName
                }}</el-descriptions-item>
              <el-descriptions-item label-align="center" label="安全库存数量">{{ curRow.safe_num }}</el-descriptions-item>
              <el-descriptions-item label-align="center" label="单位">{{ curRow.units }}</el-descriptions-item>
              <el-descriptions-item label-align="center" label="用途">{{ curRow.remark }}</el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
          <el-tab-pane label="入库信息" name="2">
            <el-table :data="curRow.inWarehouseList">
              <el-table-column label="入库单号" show-overflow-tooltip align="center" prop="sn">
              </el-table-column>
              <el-table-column label="入库名称" width="120" show-overflow-tooltip align="center" prop="name">
              </el-table-column>
              <el-table-column label="入库数量" align="center" prop="num">
              </el-table-column>
              <el-table-column label="入库时间" width="120" align="center" show-overflow-tooltip
                prop="ext1.storeDate"></el-table-column>
              <el-table-column label="仓库" align="center" show-overflow-tooltip prop="warehouseName"></el-table-column>
              <el-table-column label="库位" align="center" show-overflow-tooltip prop="shelf_info"></el-table-column>
              <el-table-column label="仓库管理员" align="center" width="120" show-overflow-tooltip
                prop="managerName"></el-table-column>
              <el-table-column label="实时库存" align="center" show-overflow-tooltip prop="current_stock"></el-table-column>
              <el-table-column label="在库时长(天)" align="center" width="150" show-overflow-tooltip
                prop="in_warehouse_days"></el-table-column>
              <el-table-column label="剩余寿命(天)" align="center" width="150" show-overflow-tooltip
                prop="remaining_life_days"></el-table-column>
              <el-table-column label="寿命超期(天)" align="center" width="150" show-overflow-tooltip
                prop="life_exceeded_days">
                <template #default="{ row }">
                  {{ row.life_exceeded_days || '--' }}
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="出库信息" name="3">
            <el-table :data="curRow.outWarehouseList" max-height="300">
              <el-table-column label="出库单号" align="center" show-overflow-tooltip prop="sn">
              </el-table-column>
              <el-table-column label="出库名称" align="center" show-overflow-tooltip prop="name"></el-table-column>
              <el-table-column label="出库说明" align="center" show-overflow-tooltip prop="remark"></el-table-column>
              <el-table-column label="仓库" align="center" >
                <template #default="{ row }">
                  {{ formatWarehouse(row.warehouseId) }}
                </template>
              </el-table-column>
              <el-table-column label="库位" align="center" prop="shelfInfo"></el-table-column>
              <el-table-column label="出库数量" align="center" prop="num"></el-table-column>
              <el-table-column label="出库人" align="center" prop="createName"></el-table-column>
              <el-table-column label="领用人" align="center" prop="recipientsName"></el-table-column>
              <el-table-column label="出库时间" align="center" show-overflow-tooltip prop="ext1.removeDate"></el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-drawer>
  </div>
</template>

<script setup name="RealtimeStore" lang="ts">
import { deepClone } from '@/utils';
import { getRealStorelist, getInWarehouseListByDevice, addDeviceOutWarehouse,listDeviceOutWarehouse,listWarehouse } from '@/api/sparesManage/index';
import { listUser } from '@/api/system/user/index'
import useUserStore from '@/store/modules/user';
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,
  createName: undefined,
  recipientsId: undefined,
  remark: undefined,
  ext1: <any>{
    removeDate: undefined
  },
  ext2: undefined
};
const formData = reactive({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    status: undefined,
    params: {}
  }
});
const detailDrawer = ref(false);
const detailTab = ref('1');
const curRow = ref({
  ext1: {}
} as any);
const userOptions = ref([])
const warehouseOptions = ref([])
const { queryParams, form } = toRefs(formData);
/** 查询列表 */
const getList = async () => {
  loading.value = true;
  const res = await getRealStorelist(queryParams.value);
  tableList.value = res.rows.map(item => ({
    ...item,
    ext1: JSON.parse(item.ext1),
  }))
  total.value = res.total;
  loading.value = false;
};

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

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

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

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

const handleRemove = async (row) => {
  reset();
  dialog.visible = true;
  dialog.title = '出库';
  Object.assign(curRow.value, row);
  form.value.sn = generateSerialNumber()
  form.value.createName = useUserStore().nickname
  const { data } = await getInWarehouseListByDevice(row.id)
  curRow.value.inWarehouseList = data.map(item => ({
    ...item,
    ext1: item.ext1 && JSON.parse(item.ext1),
    removeNum: 0
  }))

};

/** 提交按钮 */
const submitForm = () => {
  addFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      const { inWarehouseList } = curRow.value
      const { ext1, ...rest } = form.value
      if (inWarehouseList.every(item => item.removeNum === 0)) proxy?.$modal.msgError('请填写出库数量')
      buttonLoading.value = true
      const tmpArr = inWarehouseList.filter(item => item.removeNum > 0)
      tmpArr.forEach(async (item, index) => {
        await addDeviceOutWarehouse({
          ...rest,
          ext1: JSON.stringify(ext1),
          deviceTypeDetailId: item.device_type_detail_id,
          warehouseId: item.warehouse_id,
          shelfInfo: item.shelf_info,
          inWarehouseSn: item.sn,
          num:item.removeNum,
        })
        if (index === tmpArr.length - 1) {
          buttonLoading.value = false
          dialog.visible = false;
          proxy?.$modal.msgSuccess('出库成功')
          getList()
        }
      })
    }
  });
};
const handleDetail = async (row) => {
  detailDrawer.value = true;
  detailTab.value = '1';
  Object.assign(curRow.value, row);
  const { data } = await getInWarehouseListByDevice(row.id)
  curRow.value.inWarehouseList = data.map(item => ({
    ...item,
    ext1: item.ext1 && JSON.parse(item.ext1),
  }))
  const { rows } = await listDeviceOutWarehouse({ deviceTypeDetailId: row.id })
  curRow.value.outWarehouseList = rows.map(item => ({
    ...item,
    ext1: item.ext1 && JSON.parse(item.ext1),
  }))
};
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 getUserList = () => {
  listUser({ status: '0', pageSize: 10000, pageNum: 1 }).then(({ code, rows }) => {
    if (code === 200) {
      userOptions.value = rows
    }
  })
}
const getWarehouseList = () => {
  listWarehouse({}).then(({ code, rows }) => {
    if (code === 200) {
      warehouseOptions.value = rows
    }
  })
}
const formatWarehouse = (val) => {
  let label =''
  warehouseOptions.value.forEach(item => {
    if (item.id === val) {
      label= item.name
    }
  })
  return label
}
onMounted(() => {
  getList();
  getUserList()
  getWarehouseList()
});
</script>
<style lang="scss" scoped>
.operateBtn {
  display: flex;
  align-items: center;

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

.drawer-title {
  :deep(.el-descriptions__body) {
    margin-top: 10px;
    background-color: #F4F5F7;
    border-radius: 2px;
    padding: 10px 10px 0 10px;
  }

  :deep(.el-descriptions__label) {
    padding-bottom: 5px;
  }

  .title-name {
    color: #000;
  }
}
</style>
