<template>
  <div class="tenant">
    <div class="content">
      <byTable :source="sourceList.data" :pagination="sourceList.pagination" :config="config" :loading="loading" :selectConfig="selectConfig"
               highlight-current-row @get-list="getList">
        <template #productType="{ item }">
          <div>
            <div v-if="item.productDefinition == 1">
              {{ dictValueLabel(item.productType, productType) }}
            </div>
            <div v-else>
              {{ dictValueLabel(item.productType, materialType) }}
            </div>
          </div>
        </template>
        <template #unit="{ item }">
          <div>
            <div v-if="item.productDefinition == 1">
              {{ dictValueLabel(item.productUnit, productUnit) }}
            </div>
            <div v-else>
              {{ dictValueLabel(item.productUnit, materialUnit) }}
            </div>
          </div>
        </template>
        <template #waitQuantity="{item}">
          <div style="width:100%">
            <span style="padding: 4px" class="active">
              {{
               item.waitQuantity
              }}</span>
          </div>
        </template>
      </byTable>
    </div>

    <el-dialog title="出库" v-if="dialogVisible" v-model="dialogVisible" width="1300" v-loading="loadingDialog">
      <div style="width:100%;display:flex">
        <div style="flex:1;overflow:auto;height:calc(100vh - 270px)">
          <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="submit">
            <template #details>
              <div style="width: 100%">
                <el-button type="primary" @click="clickAdd()">添加明细</el-button>
                <el-table :data="formData.data.stockWaitDetailsList" show-summary :summary-method="getSummaries" style=" margin-top: 16px">
                  <el-table-column type="index" width="60" align="center" />
                  <el-table-column label="是否扫码" width="80">
                    <template #default="{ row, $index }">
                      <div>
                        <span style="padding: 4px" :class="[row.isScan == 1 ? 'active' : 'disActive']">
                          {{
                proxy.dictValueLabel(row.isScan, scanData)
              }}
                        </span>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="productCode" label="产品编码" width="140" />
                  <el-table-column prop="productName" label="产品名称" min-width="160" />
                  <el-table-column prop="productSpec" label="规格型号" width="120" />
                  <el-table-column prop="productUnit" label="单位" width="80" :formatter="
                                  (row) => dictValueLabel(row.productUnit, productUnit)
                " />
                  <el-table-column label="出库数量" width="160" prop="quantity">
                    <template #default="{ row, $index }">
                      <div style="width: 100%">
                        <el-form-item :prop="'stockWaitDetailsList.' + $index + '.quantity'" :rules="rules.quantity" :inline-message="true">
                          <el-input-number v-model="row.quantity" placeholder="请输入出库数量" style="width: 100%" :precision="0" :controls="false" :min="1"
                                           :disabled="row.isScan =='1'" onmousewheel="return false;" />
                        </el-form-item>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="操作" width="80" fixed="right">
                    <template #default="{ row, $index }">
                      <el-button type="primary" link @click="handleDelete($index)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </template>
          </byForm>
        </div>
        <div style="width:300px;margin-left:20px">
          <el-card class="box-card" style="height:100%;position: relative;">
            <div class="box">
              <img src="@/assets/images/scanz.png" class="img" v-if="!isScan" />
              <img src="@/assets/images/scaning.gif" class="img" v-if="isScan" />
              <div class="titlea" @click.stop="handleClickScan">
                {{btnTitle}}
              </div>
              <el-input v-model="scanValue" type="password" :disabled="!isScan" ref="scanInput" @change="handleScanValueChange" @blur="handleScanBlur"
                        class="input" />
            </div>
          </el-card>
        </div>

      </div>

      <!-- <div style="display:flex">
        <div style="width:50%">
          <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="submit">
          </byForm>
        </div>
        <div style="width:50%;padding-left:20px;padding-top:10px">
          <div>
            <el-button type="primary" @click="handleClickScan">{{btnTitle}}</el-button>
          </div>
          <div style="margin:15px 0px">
            <el-input v-model="textarea" :rows="5" type="textarea" :disabled="!isScan" ref="scanInput" />
          </div>
          <TitleInfo content="已扫码产品"></TitleInfo>
          <el-table :data="scanCodeData" style="margin-top: 10px">
            <el-table-column prop="productName" label="产品名称" />
            <el-table-column prop="productSpec" label="规格型号" width="100" />
            <el-table-column prop="productSpec" label="单价" width="100" />
          </el-table>
        </div>
      </div> -->
      <template #footer>
        <el-button @click="dialogVisible = false" size="large">取 消</el-button>
        <el-button type="primary" @click="submitForm()" size="large">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, ref } from "vue";
import byTable from "@/components/byTable/index";
import byForm from "@/components/byForm/index";
import { ElMessage } from "element-plus";
import useUserStore from "@/store/modules/user";
import TitleInfo from "@/components/TitleInfo/index.vue";

const { proxy } = getCurrentInstance();
const warehouseList = ref([]);
const productType = ref([]);
const productUnit = ref([]);
const materialType = ref([]);
const materialUnit = ref([]);

const status = ref([
  {
    label: "待出库",
    value: 0,
  },
  {
    label: "部分出库",
    value: 1,
  },
  {
    label: "出库完成",
    value: 2,
  },
]);
const businessType = ref([
  {
    label: "线边回仓",
    value: 1,
  },
  {
    label: "完工入库",
    value: 2,
  },
  {
    label: "采购到货",
    value: 3,
  },
  {
    label: "退货出库",
    value: 4,
  },
  {
    label: "京东订单",
    value: 5,
  },
  {
    label: "销售订单出库",
    value: 6,
  },
  {
    label: "生产任务出库",
    value: 7,
  },
  {
    label: "销售换货",
    value: 10,
  },
  {
    label: "工单出库",
    value: 11,
  },
  {
    label: "销售合同出库",
    value: 12,
  },
  {
    label: "售后物料出库",
    value: 13,
  },
]);
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
    keyword: "",
    status: "",
    type: 2,
  },
});
const loading = ref(false);
const selectConfig = computed(() => {
  return [
    {
      label: "出库状态",
      prop: "status",
      data: status.value,
    },
  ];
});
const config = computed(() => {
  return [
    {
      attrs: {
        label: "数据来源",
        prop: "businessType",
        width: 120,
      },
      render(type) {
        return proxy.dictValueLabel(type, businessType.value);
      },
    },
    {
      attrs: {
        label: "单号",
        prop: "businessCode",
        width: 160,
      },
    },
    {
      attrs: {
        label: "物品类型",
        slot: "productType",
        width: 120,
      },
      // render(type) {
      //   return proxy.dictValueLabel(type, productType.value);
      // },
    },
    {
      attrs: {
        label: "物品编码",
        prop: "productCode",
        width: 140,
      },
    },
    {
      attrs: {
        label: "物品名称",
        prop: "productName",
        "min-width": 200,
      },
    },
    {
      attrs: {
        label: "规格型号",
        prop: "productSpec",
        width: 140,
      },
    },
    {
      attrs: {
        label: "单位",
        width: 100,
        slot: "unit",
      },
    },
    {
      attrs: {
        label: "需出库数量",
        prop: "quantity",
        width: 120,
      },
    },
    {
      attrs: {
        label: "待出库数量",
        slot: "waitQuantity",
        width: 120,
      },
    },
    {
      attrs: {
        label: "出库状态",
        prop: "status",
        width: 140,
      },
      render(type) {
        return proxy.dictValueLabel(type, status.value);
      },
    },
    {
      attrs: {
        label: "操作",
        width: "80",
        align: "center",
      },
      renderHTML(row) {
        return [
          row.status !== 2
            ? {
                attrs: {
                  label: "出库",
                  type: "primary",
                  text: true,
                },
                el: "button",
                click() {
                  clickOperation(row);
                },
              }
            : {},
        ];
      },
    },
  ];
});
const getDict = () => {
  proxy.post("/warehouse/page", { pageNum: 1, pageSize: 999 }).then((res) => {
    if (res.rows && res.rows.length > 0) {
      warehouseList.value = res.rows.map((item) => {
        return {
          label: item.name,
          value: item.id,
        };
      });
    }
  });
  proxy
    .getDictOne(["product_type", "unit", "material_type", "material_unit"])
    .then((res) => {
      productType.value = res["product_type"].map((x) => ({
        label: x.dictValue,
        value: x.dictKey,
      }));
      productUnit.value = res["unit"].map((x) => ({
        label: x.dictValue,
        value: x.dictKey,
      }));

      materialType.value = res["material_type"].map((x) => ({
        label: x.dictValue,
        value: x.dictKey,
      }));
      materialUnit.value = res["material_unit"].map((x) => ({
        label: x.dictValue,
        value: x.dictKey,
      }));
    });
};
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy
    .post("/stockWaitDetails/page", sourceList.value.pagination)
    .then((res) => {
      sourceList.value.data = res.rows.map((x) => ({
        ...x,
        waitQuantity: (x.quantity - x.receiptQuantity).toFixed(4),
      }));
      sourceList.value.pagination.total = res.total;
      setTimeout(() => {
        loading.value = false;
      }, 200);
    });
};
getDict();
getList();
const dialogVisible = ref(false);
const loadingDialog = ref(false);
const submit = ref(null);
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const formData = reactive({
  data: {},
});
const formConfig = computed(() => {
  return [
    {
      label: "待出库信息",
    },
    {
      type: "select",
      prop: "businessType",
      label: "数据来源",
      disabled: true,
      data: businessType.value,
    },
    {
      type: "input",
      prop: "businessCode",
      label: "单号",
      itemType: "text",
      disabled: true,
    },
    {
      type: "input",
      prop: "productName",
      label: "物品名称",
      itemType: "text",
      disabled: true,
    },
    {
      type: "input",
      prop: "productSpec",
      label: "规格型号",
      itemType: "text",
      disabled: true,
    },
    {
      type: "input",
      prop: "quantity",
      label: "需出库数量",
      itemType: "text",
      disabled: true,
    },
    {
      type: "input",
      prop: "waitQuantity",
      label: "待出库数量",
      itemType: "text",
      disabled: true,
    },
    {
      label: "本次出库",
    },
    {
      type: "select",
      prop: "warehouseId",
      label: "仓库名称",
      required: true,
      data: warehouseList.value,
    },
    // {
    //   type: "number",
    //   prop: "warehousingQuantity",
    //   label: "出库数量",
    //   precision: 0,
    //   min: 1,
    //   controls: false,
    // },
    {
      type: "slot",
      slotName: "details",
      label: "出库明细",
    },
    {
      type: "input",
      prop: "exWarehousePerson",
      label: "出库人",
      itemWidth: 50,
    },
    {
      type: "input",
      prop: "receivingPerson",
      label: "接收人",
      itemWidth: 50,
    },
  ];
});
const rules = ref({
  warehouseId: [{ required: true, message: "请选择仓库", trigger: "change" }],
  warehousingQuantity: [
    { required: true, message: "请输入出库数量", trigger: "blur" },
  ],
  quantity: [{ required: true, message: "请输入出库数量", trigger: "blur" }],
  exWarehousePerson: [
    { required: true, message: "请输入出库人", trigger: "blur" },
  ],
  receivingPerson: [
    { required: true, message: "请输入接收人", trigger: "blur" },
  ],
});
const submitForm = () => {
  submit.value.handleSubmit(() => {
    loadingDialog.value = true;
    if (!(formData.data.stockWaitDetailsList.length > 0)) {
      return ElMessage({
        message: "请添加出库明细",
        type: "info",
      });
    }
    const total = formData.data.stockWaitDetailsList.reduce(
      (val, x) => (val += x.quantity),
      0
    );
    if (Number(total) > Number(formData.data.waitQuantity)) {
      return ElMessage({
        message: "出库数量不可大于待出库数量",
        type: "info",
      });
    }
    proxy
      .post("/stockWait/add", {
        id: formData.data.stockWaitId,
        warehouseId: formData.data.warehouseId,
        quantity: formData.data.warehousingQuantity,
        exWarehousePerson: formData.data.exWarehousePerson,
        receivingPerson: formData.data.receivingPerson,
        stockWaitDetailsList: formData.data.stockWaitDetailsList,
      })
      .then(
        () => {
          ElMessage({
            message: "提交成功",
            type: "success",
          });
          dialogVisible.value = false;
          getList();
        },
        (err) => {
          console.log(err);
          loadingDialog.value = false;
        }
      );
  });
};
const rowData = ref({});
const clickOperation = (row) => {
  rowData.value = row;
  formData.data = row;
  formData.data.stockWaitDetailsList = [];
  formData.data.exWarehousePerson = useUserStore().user.nickName;
  loadingDialog.value = false;
  dialogVisible.value = true;
};

const scanData = ref([
  {
    label: "是",
    value: "1",
  },
  {
    label: "否",
    value: "0",
  },
]);
const scanValue = ref("");
const isScan = ref(false);
const btnTitle = ref("扫码出库");
const scanInput = ref(null);
const handleClickScan = () => {
  isScan.value = !isScan.value;
  btnTitle.value = isScan.value ? "扫码中···" : "扫码出库";
  if (isScan.value) {
    scanInput.value.focus();
  }
};
const handleScanBlur = () => {
  setTimeout(() => {
    scanValue.value = "";
    isScan.value = false;
    btnTitle.value = "扫码出库";
  }, 100);
};

const timer = ref(null);
const handleScanValueChange = (val) => {
  if (val) {
    let value = val;
    let arr = [];
    if (value.includes("sn")) {
      arr = value.split("=");
    }
    scanValue.value = "";
    timer.value && clearTimeout(timer.value);
    timer.value = setTimeout(() => {
      if (arr.length > 1) {
        return proxy
          .post("/productionTaskDetail/snInfo", {
            productSn: arr[arr.length - 1],
          })
          .then(
            (res) => {
              if (res.productId != rowData.value.productId) {
                ElMessage({
                  message: "请扫正确的产品",
                  type: "info",
                });
              } else {
                formData.data.stockWaitDetailsList.push({
                  id: rowData.value.id,
                  isScan: "1",
                  productCode: res.productCode,
                  productId: res.productId,
                  productName: res.productName,
                  productSpec: res.productSpec,
                  productUnit: res.productUnit,
                  quantity: 1,
                  purchaseDetailId: "",
                });
              }
            },
            (err) => {}
          );
      }

      proxy.post("/purchaseDetail/detail", { id: value }).then(
        (res) => {
          if (res.bussinessId != rowData.value.productId) {
            ElMessage({
              message: "请扫正确的产品",
              type: "info",
            });
          } else {
            formData.data.stockWaitDetailsList.push({
              id: rowData.value.id,
              isScan: "1",
              productCode: res.productCode,
              productId: res.bussinessId,
              productName: res.productName,
              productSpec: res.productSpec,
              productUnit: res.productUnit,
              quantity: 1,
              purchaseDetailId: val,
            });
          }
        },
        (err) => {}
      );
    }, 301);
  }
};

const getSummaries = (param) => {
  const { columns, data } = param; //columns是每列的信息，data是每行的信息
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计"; //此处是在index=0的这一列显示为“合计”
      return;
    }
    const values = data.map((item) => Number(item[column.property]));
    if (column.property === "quantity") {
      sums[index] = values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!isNaN(value)) {
          return Number(parseFloat(prev + curr).toFixed(4));
        } else {
          return prev;
        }
      }, 0);
      sums[index];
    }
  });
  return sums;
};

const clickAdd = () => {
  formData.data.stockWaitDetailsList.push({
    id: formData.data.id,
    isScan: "0",
    productCode: formData.data.productCode,
    productId: formData.data.productId,
    productName: formData.data.productName,
    productSpec: formData.data.productSpec,
    productUnit: formData.data.productUnit,
    quantity: undefined,
    purchaseDetailId: "",
  });
};

const handleDelete = (index) => {
  formData.data.stockWaitDetailsList.splice(index, 1);
};
</script>

<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
::v-deep(.el-input-number .el-input__inner) {
  text-align: left;
}

.active {
  background: #a6dd82;
  color: #fff;
  border-radius: 4px;
}
.box {
  position: absolute;
  top: 50%;
  transform: translate(0, -50%);
  .img {
    width: 260px;
    height: 260px;
    object-fit: contain;
    vertical-align: middle;
    // cursor: pointer;
    z-index: 10;
  }
  .titlea {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-size: 30px;
    font-weight: 700;
    color: #5df5e9;
    cursor: pointer;
  }
  .input {
    opacity: 0;
    position: absolute;
    top: 0;
    left: 0;
  }
}

.active {
  background: #a6dd82;
  color: #fff;
  border-radius: 4px;
}
.disActive {
  background: #fa9841;
  color: #fff;
  border-radius: 4px;
}
</style>
