<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="customerId">
              <el-select
                v-model="formData.data.customerId"
                placeholder="请选择"
                @change="handleChangeCustomer"
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="item in customerList"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="选择合同" prop="contractIds">
          <el-select
            v-model="formData.data.contractIds"
            placeholder="请选择"
            @change="handleChangeContract"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in contractData"
              :label="item.code"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="合同明细" prop="contractProductData">
          <el-table :data="contractProductData" @select="handleSelectProduct">
            <el-table-column type="selection" label="" width="50" />
            <el-table-column prop="code" label="合同编码" />
            <el-table-column prop="productName" label="产品名称" />
            <el-table-column prop="cpQuantity" label="合同数量" />
            <el-table-column prop="waitQuantity" label="待装箱数量" />
            <el-table-column prop="quantity" label="装箱数量" min-width="150">
              <template #default="{ row, $index }">
                <el-form-item
                  :prop="'contractProductData.' + $index + '.quantity'"
                  :rules="rules.quantity"
                  :inline-message="true"
                >
                  <el-input-number
                    v-model="row.quantity"
                    :precision="4"
                    :controls="false"
                    :min="0"
                  />
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
          <el-button
            type="primary"
            style="margin-top: 10px; width: 100%"
            @click="handleClickPacking"
          >
            装箱
          </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" 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({
  quantity: [{ required: true, message: "请输入装箱数量", trigger: "blur" }],
});
const { proxy } = getCurrentInstance();
const selectConfig = reactive([
  {
    label: "出货状态",
    prop: "shipmentStatus",
    data: [
      {
        label: "未出货",
        value: "0",
      },
      {
        label: "出货",
        value: "1",
      },
    ],
  },
]);
const config = computed(() => {
  return [
    {
      type: "selection",
      // attrs: {
      //   checkAtt: "isCheck",
      // },
    },
    {
      attrs: {
        label: "合同号",
        prop: "subscribeCode",
      },
    },
    {
      attrs: {
        label: "产品名称",
        prop: "subscribeCode",
      },
    },

    {
      attrs: {
        label: "总箱数",
        prop: "packQuantity",
      },
    },
    {
      attrs: {
        label: "净重",
        prop: "netWeight",
      },
    },
    {
      attrs: {
        label: "毛重",
        prop: "roughWeight",
      },
    },
    {
      attrs: {
        label: "长",
        prop: "boxLong",
      },
    },

    {
      attrs: {
        label: "宽",
        prop: "boxWide",
      },
    },
    {
      attrs: {
        label: "高",
        prop: "boxHigh",
      },
    },
    {
      attrs: {
        label: "总体积",
        prop: "bomVolume",
      },
    },

    {
      attrs: {
        label: "出货状态",
        prop: "shipmentStatus",
      },
      render(status) {
        return status == 1 ? "出货" : "未出货";
      },
    },

    {
      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: {},
});

const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy
    .post("/packDetail/page", 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 = () => {
  formData.data = {};
  dialogVisible.value = true;
  handleChangeCustomer("");
};

const submitForm = () => {
  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;
      }
    );
  });
};

const selectData = ref([]);
const selectRow = (data) => {
  selectData.value = data;
};
const selectProductData = ref([]);
const handleSelectProduct = (data) => {
  selectProductData.value = data;
};
const handleClickPacking = () => {
  if (selectProductData.value.length > 0) {
    const packDetailProductList = selectProductData.value.map((x) => ({
      contractId: "",
      contractProductId: "",
      quantity: "",
    }));
    this.formData.packDetailList.push({
      customerId: "",
      contractIds: "",
      packQuantity: "",
      netWeight: "",
      roughWeight: "",
      boxLong: "",
      boxWide: "",
      boxHigh: "",
      bomVolume: "",
      remark: "",
      packDetailGoodsList: [],
      packDetailProductList: [],
    });
  } else {
    return ElMessage({
      message: "请选择产品 !",
      type: "info",
    });
  }
};
const customerList = ref([]);
const getSelectData = () => {
  proxy.post("/customer/page", { pageNum: 1, pageSize: 999 }).then((res) => {
    customerList.value = res.rows.map((item) => {
      return {
        ...item,
        label: item.name,
        value: item.id,
      };
    });
  });
};
const contractData = ref([]);
const handleChangeCustomer = (val) => {
  proxy
    .get(`/contract/getNoPackContractByCustomerId?customerId=${val}`)
    .then((res) => {
      contractData.value = res.data;
      formData.data.contractIds = "";
    });
};
const contractProductData = ref([]);
const handleChangeContract = (val) => {
  proxy
    .get(
      `/contract/getNoPackContractProductById?customerId=${formData.data.customerId}&contractId=${val}`
    )
    .then((res) => {
      contractProductData.value = res.data.map((x) => ({
        ...x,
        waitQuantity: Number(x.cpQuantity) - Number(x.sumPackQuantity),
      }));
    });
};
getSelectData();
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>