<template>
  <div class="tenant">
    <!-- <Banner /> -->
    <div class="content">
      <byTable
        :source="sourceList.data"
        :pagination="sourceList.pagination"
        :config="config"
        :loading="loading"
        highlight-current-row
        :selectConfig="selectConfig"
        :table-events="{
          //element talbe事件都能传
          select: selectRow,
          'select-all': selectRow,
        }"
        :action-list="[
          {
            text: '出货',
            disabled: selectData.length === 0,
            action: () => openModal(),
          },
          {
            text: '产品装箱',
            action: () => openModal(),
          },
        ]"
        @get-list="getList"
      >
        <template #fileSlot="{ item }">
          <div
            style="cursor: pointer; color: #409eff"
            @click="handleClickFile(item)"
          >
            {{ item.fileName }}
          </div>
        </template>
      </byTable>
    </div>
    <el-dialog
      title="产品装箱"
      v-model="dialogVisible"
      width="800"
      v-loading="loading"
    >
      <el-form
        :model="formData.data"
        :rules="rules"
        ref="formDom"
        label-position="top"
      >
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="客户名称" prop="supplyId">
              <el-select
                v-model="formData.data.supplyId"
                placeholder="请选择"
                @change="handleChangeSupplier"
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="item in supplierData"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="选择合同" prop="supplyId">
          <el-select
            v-model="formData.data.supplyId"
            placeholder="请选择"
            @change="handleChangeSupplier"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in supplierData"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="合同明细" prop="purchaseContent">
          <el-table :data="formData.data.purchaseDetailList">
            <el-table-column type="selection" label="" width="50" />
            <el-table-column prop="productCode" label="合同编码" />
            <el-table-column prop="productName" label="产品名称" />
            <el-table-column prop="productSpec" label="合同数量" />
            <el-table-column prop="productUnit" label="待装箱数量" />
            <el-table-column prop="count" label="装箱数量" min-width="150">
              <template #default="{ row, $index }">
                <el-form-item
                  :prop="'purchaseDetailList.' + $index + '.count'"
                  :rules="rules.count"
                  :inline-message="true"
                >
                  <el-input-number
                    v-model="row.count"
                    :precision="4"
                    :controls="false"
                    :min="0"
                  />
                </el-form-item>
              </template>
            </el-table-column>

            <!-- <el-table-column prop="zip" label="操作" width="100">
              <template #default="{ $index }">
                <el-button type="primary" link @click="handleRemove($index)"
                  >删除</el-button
                >
              </template>
            </el-table-column> -->
          </el-table>
          <el-button
            type="primary"
            @click="openProduct = true"
            style="margin-top: 10px; width: 100%"
          >
            装箱
          </el-button>
        </el-form-item>

        <el-form-item label="装箱明细">
          <div class="box">
            <div ref="">箱规</div>
            <el-row :gutter="10">
              <el-col :span="5">
                <el-form-item label="箱数" prop="supplyId">
                  <el-input
                    v-model="formData.data.a"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="净重(kg)" prop="supplyId">
                  <el-input
                    v-model="formData.data.a"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="毛重(kg)" prop="supplyId">
                  <el-input
                    v-model="formData.data.a"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="9">
                <el-row>
                  <el-form-item label="尺寸（cm³）" required>
                    <el-col :span="1"></el-col>
                    <el-col :span="7">
                      <el-input
                        v-model="formData.data.a"
                        placeholder="长"
                      ></el-input>
                    </el-col>
                    <el-col :span="1" style="text-align: center"> * </el-col>
                    <el-col :span="7">
                      <el-input
                        v-model="formData.data.a"
                        placeholder="宽"
                      ></el-input>
                    </el-col>
                    <el-col :span="1" style="text-align: center"> * </el-col>
                    <el-col :span="7">
                      <el-input
                        v-model="formData.data.a"
                        placeholder="高"
                      ></el-input>
                    </el-col>
                  </el-form-item>
                </el-row>
              </el-col>
            </el-row>
            <div class="line"></div>
            <el-form-item label="关联合同产品">
              <div class="flex-box">
                <div class="item">
                  <div>合同编码：PO-2301-001</div>
                  <div>产品名称：PO-2301-001</div>
                  <div>每箱数量：PO-2301-001</div>
                </div>
              </div>
            </el-form-item>
            <div class="bottom-arrow" v-show="fade">
              <span style="margin-right: 5px"> 自定义装箱明细</span>
              <el-icon><ArrowDownBold /></el-icon>
            </div>
            <div class="bottom-arrow" v-show="true">
              <span style="margin-right: 5px"> 收起</span>
              <el-icon><ArrowUpBold /></el-icon>
            </div>
            <el-form-item prop="自定义装箱">
              <el-button
                type="primary"
                @click="openProduct = true"
                style="margin-bottom: 10px"
              >
                添加行
              </el-button>
              <el-table :data="formData.data.purchaseDetailList">
                <el-table-column prop="count" label="货物描述">
                  <template #default="{ row, $index }">
                    <el-form-item
                      :prop="'purchaseDetailList.' + $index + '.count'"
                      :rules="rules.count"
                      :inline-message="true"
                    >
                      <el-input v-model="row.count" placeholder="请输入" />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column prop="count" label="单位" width="150">
                  <template #default="{ row, $index }">
                    <el-form-item
                      :prop="'purchaseDetailList.' + $index + '.count'"
                      :rules="rules.count"
                      :inline-message="true"
                    >
                      <el-input-number
                        v-model="row.count"
                        :precision="4"
                        :controls="false"
                        :min="0"
                      />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column prop="count" label="数量" width="150">
                  <template #default="{ row, $index }">
                    <el-form-item
                      :prop="'purchaseDetailList.' + $index + '.count'"
                      :rules="rules.count"
                      :inline-message="true"
                    >
                      <el-input-number
                        v-model="row.count"
                        :precision="4"
                        :controls="false"
                        :min="0"
                      />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column prop="zip" label="操作" width="100">
                  <template #default="{ $index }">
                    <el-button type="primary" link @click="handleRemove($index)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false" size="large">取 消</el-button>
        <el-button
          type="primary"
          @click="submitForm('byform')"
          size="large"
          :loading="submitLoading"
        >
          确 定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>
  
<script setup>
/* eslint-disable vue/no-unused-components */
import { ElMessage, ElMessageBox } from "element-plus";
import byTable from "@/components/byTable/index";
import byForm from "@/components/byForm/index";
import FileUpload from "@/components/FileUpload/index";
import { computed, defineComponent, ref } from "vue";
import { getToken } from "@/utils/auth";

const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + "/common/upload"); // 上传文件服务器地址
const headers = ref({ Authorization: "Bearer " + getToken() });
const uploadData = ref({});
const loading = ref(false);
const submitLoading = ref(false);
const sourceList = ref({
  data: [],
  pagination: {
    total: 3,
    pageNum: 1,
    pageSize: 10,
    status: "",
  },
});
let dialogVisible = ref(false);
let modalType = ref("add");
let fileList = ref([]);
let rules = ref({
  name: [{ required: true, message: "请输入供应商名称", trigger: "blur" }],
});
const { proxy } = getCurrentInstance();
const selectConfig = reactive([
  {
    label: "出货状态",
    prop: "productType",
    data: [
      {
        label: "产品",
        value: "1",
      },
      {
        label: "物料",
        value: "2",
      },
    ],
  },
]);
const config = computed(() => {
  return [
    {
      type: "selection",
      // attrs: {
      //   checkAtt: "isCheck",
      // },
    },
    {
      attrs: {
        label: "合同号",
        prop: "subscribeCode",
      },
    },
    {
      attrs: {
        label: "产品名称",
        prop: "subscribeCode",
      },
    },

    {
      attrs: {
        label: "总箱数",
        prop: "productCategory",
      },
    },
    {
      attrs: {
        label: "净重",
        prop: "productCode",
      },
    },
    {
      attrs: {
        label: "毛重",
        prop: "productName",
      },
    },
    {
      attrs: {
        label: "长",
        prop: "productUnit",
      },
    },

    {
      attrs: {
        label: "宽",
        prop: "count",
      },
    },
    {
      attrs: {
        label: "高",
        prop: "receiptWarehouseName",
      },
    },
    {
      attrs: {
        label: "总体积",
        prop: "planArrivalTime",
      },
    },

    {
      attrs: {
        label: "出货状态",
        prop: "status",
      },
      render(status) {
        return statusData.value.find((x) => x.value == status).label;
      },
    },

    {
      attrs: {
        label: "操作",
        width: "200",
        align: "right",
      },
      // 渲染 el-button，一般用在最后一列。
      renderHTML(row) {
        return [
          {
            attrs: {
              label: "打印",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              getDtl(row);
            },
          },
          {
            attrs: {
              label: "删除",
              type: "danger",
              text: true,
              disabled: row.status != 30,
            },
            el: "button",
            click() {
              // 弹窗提示是否删除
              ElMessageBox.confirm(
                "此操作将永久作废该数据, 是否继续?",
                "提示",
                {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning",
                }
              ).then(() => {
                // 删除
                proxy
                  .post("/subscribeDetail/edit", {
                    ...row,
                    status: 99,
                  })
                  .then((res) => {
                    ElMessage({
                      message: "作废成功",
                      type: "success",
                    });
                    getList();
                  });
              });
            },
          },
        ];
      },
    },
  ];
});

let formData = reactive({
  data: {
    type: "1",
  },
});
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const byform = ref(null);
const formConfig = computed(() => {
  return [
    {
      type: "radio",
      prop: "name",
      label: "供应商类型",
      required: true,
      border: true,
      data: [
        { label: "贸易商", value: "1" },
        { label: "工厂", value: "2" },
      ],
    },
    {
      type: "input",
      prop: "name",
      label: "供应商名称",
      required: true,
    },
    {
      type: "slot",
      slotName: "address",
      label: "地址",
      required: true,
    },
    {
      type: "slot",
      slotName: "contact",
      label: "联系信息",
      required: true,
    },
    {
      type: "slot",
      slotName: "fileSlot",
      label: "上传附件",
    },
    {
      type: "input",
      label: "备注",
      prop: "remakes",
      itemType: "textarea",
    },
  ];
});
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy
    .post("/subscribeDetail/pageByWdly  ", sourceList.value.pagination)
    .then((message) => {
      console.log(message);
      sourceList.value.data = message.rows.map((x) => ({
        ...x,
        ...JSON.parse(x.victoriatouristJson),
      }));
      sourceList.value.pagination.total = message.total;
      setTimeout(() => {
        loading.value = false;
      }, 200);
    });
};

const openModal = () => {
  dialogVisible.value = true;
};

const submitForm = () => {
  if (fileList.value.length > 0) {
    byform.value.handleSubmit((valid) => {
      formData.data.fileList = fileList.value;
      submitLoading.value = true;
      proxy.post("/productionProcesses/" + modalType.value, formData.data).then(
        (res) => {
          ElMessage({
            message: modalType.value == "add" ? "添加成功" : "编辑成功",
            type: "success",
          });
          fileList.value = [];
          dialogVisible.value = false;
          submitLoading.value = false;
          getList();
        },
        (err) => {
          console.log(err, "aswwwww");
          submitLoading.value = false;
        }
      );
    });
  } else {
    return ElMessage({
      message: "请上传附件！",
      type: "info",
    });
  }
};

const getDtl = (row) => {
  modalType.value = "edit";
  proxy.post("/productionProcesses/detail", { id: row.id }).then((res) => {
    fileList.value = [
      {
        id: "",
        fileName: res.fileName,
        path: "",
      },
    ];
    formData.data = res;
    dialogVisible.value = true;
  });
};
const handleBeforeUpload = async (file) => {
  const res = await proxy.post("/fileInfo/getSing", { fileName: file.name });
  uploadData.value = res.uploadBody;
  fileList.value = [
    {
      id: res.id,
      fileName: res.fileName,
      path: res.fileUrl,
    },
  ];
};
const handleClickFile = (row) => {
  ElMessage({
    message: "数据请求中，请稍后！",
    type: "success",
  });
  let id = row.id;
  proxy.post("/fileInfo/getList", { businessIdList: [id] }).then((res) => {
    const file = res[id][0];
    window.open(file.fileUrl, "_blank");
  });
};

const handlePreview = (file) => {
  console.log(file);
};
const handleSuccess = (file) => {
  console.log(file);
};
const handleRemove = (file) => {
  fileList.value = [];
};
const handleClose = (index) => {
  fileList.value.splice(index, 1);
};
const statusData = ref([
  {
    label: "审批中",
    value: "10",
  },
  {
    label: "待采购",
    value: "15",
  },
  {
    label: "部分采购",
    value: "30",
  },
  {
    label: "已采购",
    value: "20",
  },
  {
    label: "已作废",
    value: "99",
  },
]);

const selectData = ref([]);
const selectRow = (data) => {
  selectData.value = data;
};

// selectConfig[1].data = statusData.value;
getList();
</script>
  
<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
:deep(.el-collapse-item__header) {
  background-color: #fde6c8;
  border: none;
}
:deep(.el-collapse-item__wrap) {
  background-color: #fde6c8;
  border: none;
}

.box {
  padding: 15px;
  background: #fde6c8;
  border: 1px solid #7fb5e3;
  .flex-box {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    .item {
      width: 50%;
      div {
        line-height: 22px;
      }
    }
  }
  .line {
    width: 100%;
    height: 1px;
    background: #7fb5e3;
    margin: 10px 0;
  }
  .bottom-arrow {
    text-align: center;
    cursor: pointer;
    color: #0084ff;
  }
}
</style>