<template>
  <div>
    <el-card class="box-card">
      <byTable
        :source="sourceList.data"
        :pagination="sourceList.pagination"
        :config="config"
        :loading="loading"
        :searchConfig="searchConfig"
        highlight-current-row
        :action-list="[
          {
            text: '登记对账',
            action: () => clickModal(),
          },
        ]"
        @get-list="getList"
        @clickReset="clickReset">
        <template #timePeriod="{ item }">
          <div>
            <el-row>
              <el-col :span="11">{{ item.timePeriod }}</el-col>
              <el-col :span="2" style="text-align: center">-</el-col>
              <el-col :span="11">{{ item.timePeriod }}</el-col>
            </el-row>
          </div>
        </template>
        <template #receiptFileList="{ item }">
          <div>
            <el-button type="primary" @click="clickReceiptFile(item)" v-if="item.receiptFileList && item.receiptFileList.length > 0" text>查看</el-button>
            <el-button type="danger" @click="clickReceiptFile(item)" v-else text>上传</el-button>
          </div>
        </template>
        <template #proofFileList="{ item }">
          <div>
            <el-button type="primary" @click="clickProofFile(item)" v-if="item.proofFileList && item.proofFileList.length > 0" text>查看</el-button>
            <el-button type="danger" @click="clickProofFile(item)" v-else text>上传</el-button>
          </div>
        </template>
      </byTable>
    </el-card>

    <el-dialog :title="modalType == 'add' ? '登记对账' : '编辑对账'" v-if="openDialog" v-model="openDialog" width="80%">
      <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data">
        <template #orderIdList>
          <div style="width: 100%">
            <el-form-item label="事业部" prop="departmentId" style="margin-bottom: 18px">
              <el-select v-model="formData.data.departmentId" placeholder="请选择事业部" clearable @change="changeDepartment" :disabled="formData.data.id">
                <el-option v-for="item in departmentList" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey" />
              </el-select>
              <el-button type="primary" size="small" style="margin-left: 16px" @click="clickAddOrder()">选择合同</el-button>
            </el-form-item>
            <el-table :data="formData.data.orderList" :row-style="{ height: '35px' }" header-row-class-name="tableHeader">
              <el-table-column label="事业部" prop="departmentName" width="140" />
              <el-table-column label="订单号" prop="orderCode" min-width="180" />
              <el-table-column label="订单总金额 ¥" prop="totalAmount" align="right" width="120" />
              <el-table-column label="产品总金额 ¥" prop="productTotalAmount" align="right" width="120" />
              <el-table-column label="定制加工费 ¥" prop="customProcessingFee" align="right" width="110" />
              <el-table-column label="代发费 ¥" prop="lssueFee" align="right" width="100" />
              <el-table-column label="快递包材费 ¥" prop="deliveryMaterialsFee" align="right" width="110" />
              <el-table-column label="包装人工费 ¥" prop="packingLabor" align="right" width="110" />
              <el-table-column label="包材费 ¥" prop="packagingMaterialCost" align="right" width="100" />
              <el-table-column label="管理费 ¥" prop="managementFee" align="right" width="100" />
              <el-table-column label="操作" align="center" fixed="right" width="60">
                <template #default="{ $index }">
                  <el-button type="danger" @click="clickOrderDelete($index)" text>删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="openDialog = false" size="large">取 消</el-button>
        <el-button type="primary" @click="submitForm()" size="large" v-preReClick>确 定</el-button>
      </template>
    </el-dialog>

    <el-dialog title="上传对账单" v-if="openReceiptFile" v-model="openReceiptFile" width="600">
      <el-upload
        v-model:fileList="fileList"
        action="https://winfaster.obs.cn-south-1.myhuaweicloud.com"
        :data="uploadReceiptData"
        multiple
        :before-upload="uploadReceiptFile"
        :on-success="handleReceiptSuccess"
        :on-preview="onPreviewFile">
        <el-button type="primary">上传</el-button>
      </el-upload>
      <template #footer>
        <el-button @click="openReceiptFile = false" size="large">取 消</el-button>
        <el-button type="primary" @click="submitReceiptFile()" size="large" v-preReClick>确 定</el-button>
      </template>
    </el-dialog>

    <el-dialog title="上传转账凭证" v-if="openProofFile" v-model="openProofFile" width="600">
      <el-upload
        v-model:fileList="fileList"
        action="https://winfaster.obs.cn-south-1.myhuaweicloud.com"
        :data="uploadProofData"
        multiple
        :before-upload="uploadProofFile"
        :on-success="handleProofSuccess"
        :on-preview="onPreviewFile">
        <el-button type="primary">上传</el-button>
      </el-upload>
      <template #footer>
        <el-button @click="openProofFile = false" size="large">取 消</el-button>
        <el-button type="primary" @click="submitProofFile()" size="large" v-preReClick>确 定</el-button>
      </template>
    </el-dialog>

    <el-dialog title="选择合同" v-if="openOrder" v-model="openOrder" width="90%">
      <SelectOrder :selectStatus="true" :departmentId="formData.data.departmentId" @selectOrder="selectOrder"></SelectOrder>
      <template #footer>
        <el-button @click="openOrder = false" size="large">关 闭</el-button>
      </template>
    </el-dialog>

    <el-dialog title="打印" v-if="openPrint" v-model="openPrint" width="94%" class="print">
      <el-tabs v-model="tabsCard" type="card">
        <el-tab-pane v-for="(item, index) in cardList" :key="index" :label="item.dictValue" :name="item.dictKey"> </el-tab-pane>
      </el-tabs>
      <div style="padding: 0 10px">
        <el-tabs v-model="activeName">
          <el-tab-pane label="SKU对账单" name="sku">
            <PrintSKU :rowData="rowData" :tabValues="{ activeName: activeName, tabsCard: tabsCard }" @clickCancel="openPrint = false"></PrintSKU>
          </el-tab-pane>
          <el-tab-pane label="BOM对账单" name="bom">
            <PrintBOM :rowData="rowData" :tabValues="{ activeName: activeName, tabsCard: tabsCard }" @clickCancel="openPrint = false"></PrintBOM>
          </el-tab-pane>
          <el-tab-pane label="订单对账单" name="order">
            <PrintOrder :rowData="rowData" :tabValues="{ activeName: activeName, tabsCard: tabsCard }" @clickCancel="openPrint = false"></PrintOrder>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import byTable from "/src/components/byTable/index";
import byForm from "/src/components/byForm/index";
import { ElMessage, ElMessageBox } from "element-plus";
import SelectOrder from "/src/views/group/order/management/index";
import PrintSKU from "/src/views/group/finance/check-bill/printSKU.vue";
import PrintBOM from "/src/views/group/finance/check-bill/printBOM.vue";
import PrintOrder from "/src/views/group/finance/check-bill/printOrder.vue";
import { copyText } from "vue3-clipboard";

const { proxy } = getCurrentInstance();
const departmentList = ref([{ dictKey: "0", dictValue: "胜德体育" }]);
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
    code: "",
    departmentId: "",
    beginTime: "",
    endTime: "",
  },
});
const loading = ref(false);
const searchConfig = computed(() => {
  return [
    {
      type: "input",
      prop: "code",
      label: "对账单号",
    },
    {
      type: "select",
      prop: "departmentId",
      data: departmentList.value,
      label: "事业部",
    },
    {
      type: "date",
      propList: ["beginTime", "endTime"],
      label: "对账日期",
    },
  ];
});
const config = computed(() => {
  return [
    {
      attrs: {
        label: "对账单号",
        prop: "code",
      },
    },
    {
      attrs: {
        label: "创建时间",
        prop: "createTime",
        width: 160,
      },
    },
    {
      attrs: {
        label: "客户",
        prop: "departmentName",
      },
    },
    {
      attrs: {
        label: "对账金额",
        prop: "amount",
        align: "right",
        width: 180,
      },
    },
    {
      attrs: {
        label: "合同数量",
        prop: "orderNum",
        width: 100,
      },
    },
    {
      attrs: {
        label: "对账时间",
        prop: "timePeriod",
        align: "center",
        width: 180,
      },
    },
    {
      attrs: {
        label: "对账单",
        slot: "receiptFileList",
        align: "center",
        width: 120,
      },
    },
    {
      attrs: {
        label: "转账凭证",
        slot: "proofFileList",
        align: "center",
        width: 120,
      },
    },
    {
      attrs: {
        label: "操作",
        width: 180,
        align: "center",
        fixed: "right",
      },
      renderHTML(row) {
        return [
          {
            attrs: {
              label: "复制单号",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              clickCopyWLNCode(row);
            },
          },
          {
            attrs: {
              label: "打印",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              clickPrint(row);
            },
          },
          {
            attrs: {
              label: "编辑",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              clickUpdate(row);
            },
          },
          {
            attrs: {
              label: "删除",
              type: "danger",
              text: true,
            },
            el: "button",
            click() {
              clickDelete(row);
            },
          },
        ];
      },
    },
  ];
});
const getDemandData = () => {
  proxy.post("/department/page", { pageNum: 1, pageSize: 999 }).then((res) => {
    if (res.rows && res.rows.length > 0) {
      departmentList.value = departmentList.value.concat(
        res.rows.map((item) => {
          return {
            dictKey: item.id,
            dictValue: item.name,
          };
        })
      );
    }
  });
};
getDemandData();
const getList = async (req, status) => {
  if (status) {
    sourceList.value.pagination = {
      pageNum: sourceList.value.pagination.pageNum,
      pageSize: sourceList.value.pagination.pageSize,
    };
  } else {
    sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  }
  loading.value = true;
  proxy.post("/statementOfAccount/page", sourceList.value.pagination).then((res) => {
    sourceList.value.data = res.rows;
    sourceList.value.pagination.total = res.total;
    setTimeout(() => {
      loading.value = false;
    }, 200);
  });
};
getList();
const clickReset = () => {
  getList("", true);
};
const modalType = ref("add");
const openDialog = ref(false);
const formOption = reactive({
  inline: true,
  labelWidth: "120px",
  itemWidth: 100,
  rules: [],
  labelPosition: "right",
});
const formData = reactive({
  data: {},
});
const formConfig = computed(() => {
  return [
    {
      type: "title",
      title: "对账合同",
      label: "",
    },
    {
      type: "slot",
      slotName: "orderIdList",
      label: "",
    },
  ];
});
const clickModal = () => {
  modalType.value = "add";
  formData.data = {
    departmentId: "",
    amount: "",
    orderIdList: [],
    orderList: [],
  };
  openDialog.value = true;
};
const changeDepartment = () => {
  formData.data.orderList = [];
};
const openOrder = ref(false);
const clickAddOrder = () => {
  if (formData.data.departmentId) {
    openOrder.value = true;
  } else {
    return ElMessage("请先选择事业部");
  }
};
const selectOrder = (row) => {
  if (formData.data.orderList && formData.data.orderList.length > 0) {
    let list = formData.data.orderList.filter((item) => item.orderId === row.id);
    if (list && list.length > 0) {
      return ElMessage("该订单已添加");
    }
  } else {
    formData.data.orderList = [];
  }
  formData.data.orderList.push({
    orderId: row.id,
    departmentName: row.departmentName,
    orderCode: row.code,
    totalAmount: row.totalAmount,
    productTotalAmount: row.productTotalAmount,
    customProcessingFee: row.customProcessingFee,
    lssueFee: row.lssueFee,
    deliveryMaterialsFee: row.deliveryMaterialsFee,
    packingLabor: row.packingLabor,
    managementFee: row.managementFee,
    outerBoxPackingFee: row.outerBoxPackingFee,
    packagingMaterialCost: row.packagingMaterialCost,
  });
  ElMessage({ message: "添加成功", type: "success" });
};
const clickOrderDelete = (index) => {
  formData.data.orderList.splice(index, 1);
};
const submitForm = () => {
  if (formData.data.orderList && formData.data.orderList.length > 0) {
    let amount = 0;
    for (let i = 0; i < formData.data.orderList.length; i++) {
      amount = Number(Math.round((amount + formData.data.orderList[i].totalAmount) * 100) / 100);
    }
    let orderIdList = formData.data.orderList.map((item) => item.orderId);
    proxy
      .post("/statementOfAccount/" + modalType.value, {
        id: formData.data.id,
        departmentId: formData.data.departmentId,
        amount: amount,
        orderIdList: orderIdList,
      })
      .then(() => {
        ElMessage({
          message: modalType.value == "add" ? "添加成功" : "编辑成功",
          type: "success",
        });
        openDialog.value = false;
        getList();
      });
  } else {
    return ElMessage("请先添加订单");
  }
};
const clickUpdate = (row) => {
  formData.data = {
    id: row.id,
  };
  modalType.value = "edit";
  proxy.post("/statementOfAccount/detail", { id: row.id }).then((res) => {
    if (res && res.length > 0) {
      formData.data.departmentId = res[0].departmentId;
      formData.data.orderList = res;
    }
    openDialog.value = true;
  });
};
const clickDelete = (row) => {
  ElMessageBox.confirm("你是否确认此操作", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      proxy.post("/statementOfAccount/delete", { id: row.id }).then(() => {
        ElMessage({ message: "删除成功", type: "success" });
        getList();
      });
    })
    .catch(() => {});
};
const openReceiptFile = ref(false);
const formReceiptData = reactive({
  data: {
    id: "",
    fileList: [],
  },
});
const fileList = ref([]);
const clickReceiptFile = (row) => {
  formReceiptData.data = {
    id: row.id,
    fileList: [],
  };
  if (row.receiptFileList && row.receiptFileList.length > 0) {
    fileList.value = proxy.deepClone(
      row.receiptFileList.map((item) => {
        return {
          raw: item,
          name: item.fileName,
          url: item.fileUrl,
        };
      })
    );
  } else {
    fileList.value = [];
  }
  openReceiptFile.value = true;
};
const uploadReceiptData = ref({});
const uploadReceiptFile = async (file) => {
  const res = await proxy.post("/fileInfo/getSing", { fileName: file.name });
  uploadReceiptData.value = res.uploadBody;
  file.id = res.id;
  file.fileName = res.fileName;
  file.fileUrl = res.fileUrl;
  file.uploadState = true;
  return true;
};
const handleReceiptSuccess = (any, UploadFile) => {
  UploadFile.raw.uploadState = false;
};
const onPreviewFile = (file) => {
  window.open(file.raw.fileUrl, "_blank");
};
const submitReceiptFile = () => {
  if (fileList.value && fileList.value.length > 0) {
    for (let i = 0; i < fileList.value.length; i++) {
      if (fileList.value[i].raw.uploadState) {
        return ElMessage("文件上传中,请稍后提交");
      }
    }
    formReceiptData.data.fileList = fileList.value.map((item) => {
      return {
        id: item.raw.id,
        fileName: item.raw.fileName,
        fileUrl: item.raw.fileUrl,
      };
    });
  } else {
    formReceiptData.data.fileList = [];
  }
  proxy.post("/statementOfAccount/editReceiptFile", formReceiptData.data).then(() => {
    openReceiptFile.value = false;
    getList();
  });
};
const openProofFile = ref(false);
const formProofData = reactive({
  data: {
    id: "",
    fileList: [],
  },
});
const clickProofFile = (row) => {
  formProofData.data = {
    id: row.id,
    fileList: [],
  };
  if (row.proofFileList && row.proofFileList.length > 0) {
    fileList.value = proxy.deepClone(
      row.proofFileList.map((item) => {
        return {
          raw: item,
          name: item.fileName,
          url: item.fileUrl,
        };
      })
    );
  } else {
    fileList.value = [];
  }
  openProofFile.value = true;
};
const uploadProofData = ref({});
const uploadProofFile = async (file) => {
  const res = await proxy.post("/fileInfo/getSing", { fileName: file.name });
  uploadProofData.value = res.uploadBody;
  file.id = res.id;
  file.fileName = res.fileName;
  file.fileUrl = res.fileUrl;
  file.uploadState = true;
  return true;
};
const handleProofSuccess = (any, UploadFile) => {
  UploadFile.raw.uploadState = false;
};
const submitProofFile = () => {
  if (fileList.value && fileList.value.length > 0) {
    for (let i = 0; i < fileList.value.length; i++) {
      if (fileList.value[i].raw.uploadState) {
        return ElMessage("文件上传中,请稍后提交");
      }
    }
    formProofData.data.fileList = fileList.value.map((item) => {
      return {
        id: item.raw.id,
        fileName: item.raw.fileName,
        fileUrl: item.raw.fileUrl,
      };
    });
  } else {
    formProofData.data.fileList = [];
  }
  proxy.post("/statementOfAccount/editProofFile", formProofData.data).then(() => {
    openProofFile.value = false;
    getList();
  });
};
const openPrint = ref(false);
const rowData = ref({});
const cardList = ref([
  {
    dictKey: 1,
    dictValue: "万里牛订单",
  },
  {
    dictKey: 2,
    dictValue: "采购订单",
  },
  {
    dictKey: 3,
    dictValue: "委外订单",
  },
  {
    dictKey: 4,
    dictValue: "售后订单",
  },
  {
    dictKey: 5,
    dictValue: "无理由订单",
  },
]);
const tabsCard = ref(1);
const activeName = ref("sku");
const clickPrint = (row) => {
  tabsCard.value = 1;
  activeName.value = "sku";
  rowData.value = row;
  openPrint.value = true;
};
const clickCopyWLNCode = (row) => {
  ElMessage("复制数据中,请稍后");
  proxy.post("/statementOfAccount/getOrderWlnCodeStr", [row.id]).then((res) => {
    copyText(res, undefined, (error) => {
      if (error) {
        ElMessage.error(`复制失败: ${error} ！`);
      } else {
        ElMessage.success(`复制成功！`);
      }
    });
  });
};
</script>

<style lang="scss" scoped>
:deep(.el-dialog) {
  margin-top: 10px !important;
  margin-bottom: 10px !important;
}
:deep(.print) {
  .el-dialog__body {
    padding: 10px 20px !important;
    .el-tabs__header {
      margin: 0 !important;
    }
  }
}
</style>
