<template>
  <div class="page card h-100 flex-gap-10 overflow-hidden flex">
    <div class="left">
      <ElTree
        ref="treeRef"
        default-expand-all
        :expand-on-click-node="false"
        :default-expanded-keys="[]"
        :highlight-current="true"
        node-key="code"
        :data="treeData"
        :props="{ children: 'children', label: 'remark' }"
        @node-click="nodeClick"
      >
        <template #default="{ data }">
          <div class="tree-node">
            <div class="tree-node-label">{{ data.remark }}</div>
            <div v-if="data.count || data.count === 0" class="tree-node-count">
              {{ `(${data.count})` }}
            </div>
          </div>
        </template>
      </ElTree>
    </div>
    <div class="right">
      <!-- <pending-reconciliation></pending-reconciliation> -->
      <div class="delivery-note-page flex-column card h-100 overflow-hidden">
        <splitDiv size="50">
          <template #top>
            <div class="header-filter-form">
              <ElForm :model="searchForm" inline>
                <ElFormItem label="账期(发货时间)">
                  <div style="display: flex">
                    <el-date-picker
                      v-model="dateRange"
                      :default-time="[
                        new Date(0, 0, 0, 0, 0, 0),
                        new Date(0, 0, 0, 23, 59, 59),
                      ]"
                      type="datetimerange"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                      unlink-panels
                      clearable
                      style="width: 260px"
                      format="YYYY-MM-DD HH:mm:ss"
                      value-format="YYYY-MM-DD HH:mm:ss"
                    />
                  </div>
                </ElFormItem>
                <ElFormItem style="margin-right: 10px" label="对账单号">
                  <ElInput
                    v-model="searchForm.recNumber"
                    clearable
                    placeholder="对账单号"
                    style="width: 160px"
                  />
                </ElFormItem>
                <ElFormItem style="margin-right: 10px" label="订单号">
                  <ElInput
                    v-model="searchForm.orderNumber"
                    clearable
                    placeholder="订单号"
                    style="width: 160px"
                  />
                </ElFormItem>

                <ElFormItem>
                  <ElButton type="primary" @click="search">查询</ElButton>
                </ElFormItem>
                <ElFormItem>
                  <ElButton @click="reset">重置</ElButton>
                </ElFormItem>
                <ElFormItem v-if="nodeId === 15">
                  <el-button type="warning" @click="rejectOrder">
                    驳回
                  </el-button>
                </ElFormItem>
                <ElFormItem>
                  <el-button type="success" @click="exportExcel">
                    导出
                  </el-button>
                </ElFormItem>
                <ElFormItem v-if="nodeId === 30">
                  <el-button type="danger" @click="auditOrder('archive')">
                    归档
                  </el-button>
                </ElFormItem>
              </ElForm>
            </div>

            <div
              class="delivery-note-content flex-1 flex-column overflow-hidden"
            >
              <div class="delivery-note-list flex-1 overflow-hidden">
                <ElTable
                  ref="singleTableRef"
                  highlight-current-row
                  :data="tableData"
                  show-summary
                  :summary-method="getSummaries"
                  default-expand-all
                  size="small"
                  style="width: 100%; height: 100%"
                  border
                  @current-change="rowClick"
                  @selection-change="handleSelectionChange"
                >
                  <el-table-column
                    type="selection"
                    width="70"
                    header-align="center"
                    align="center"
                  />
                  <el-table-column
                    label="序号"
                    type="index"
                    width="80"
                    align="center"
                    header-align="center"
                  ></el-table-column>

                  <el-table-column
                    label="对账单号"
                    prop="rec_number"
                    header-align="center"
                    align="center"
                    min-width="160"
                    show-overflow-tooltip
                  ></el-table-column>
                  <el-table-column
                    label="账期(发货时间)"
                    header-align="center"
                    align="center"
                    min-width="340"
                  >
                    <template #default="scope">
                      {{ scope.row.start_time }} - {{ scope.row.end_time }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="底胚总价($)"
                    header-align="center"
                    prop="product_total_amount"
                    width="100"
                    align="center"
                    show-overflow-tooltip
                  >
                  </el-table-column>
                  <el-table-column
                    label="总发货(件)"
                    header-align="center"
                    prop="num"
                    width="100"
                    align="center"
                    show-overflow-tooltip
                  >
                  </el-table-column>
                  <el-table-column
                    label="工艺总价($)"
                    header-align="center"
                    prop="craft_total_price"
                    width="130"
                    align="center"
                    show-overflow-tooltip
                  ></el-table-column>
                  <el-table-column
                    label="商品总价($)"
                    header-align="center"
                    prop="product_total_amount"
                    width="130"
                    align="center"
                    show-overflow-tooltip
                  >
                  </el-table-column>

                  <el-table-column
                    label="物流总价($)"
                    header-align="center"
                    prop="carriage_total_amount"
                    width="130"
                    align="center"
                    show-overflow-tooltip
                  ></el-table-column>
                  <el-table-column
                    label="应付金额($)"
                    header-align="center"
                    prop="total_amount"
                    width="130"
                    align="center"
                    show-overflow-tooltip
                  >
                  </el-table-column>
                  <el-table-column
                    label="实付金额($)"
                    header-align="center"
                    prop="actual_amount"
                    width="130"
                    align="center"
                    show-overflow-tooltip
                  ></el-table-column>
                  <el-table-column
                    label="已付金额($)"
                    header-align="center"
                    prop="total_amount_str"
                    width="130"
                    align="center"
                    show-overflow-tooltip
                  ></el-table-column>
                  <el-table-column
                    label="水单"
                    header-align="center"
                    min-width="140"
                    align="center"
                    show-overflow-tooltip
                  >
                    <template #default="{ row }">
                      <div
                        v-if="row.water_list"
                        style="display: flex; gap: 2px; align-items: center"
                      >
                        <div
                          v-for="item in (typeof row.water_list === 'string'
                            ? row.water_list
                            : ''
                          ).split(',')"
                          :key="item"
                          style="width: 30px"
                        >
                          <ImageView :src="item" />
                        </div>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="创建时间"
                    prop="create_time"
                    width="180"
                    header-align="center"
                    align="center"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    label="操作"
                    width="100"
                    header-align="center"
                    align="center"
                    fixed="right"
                  >
                    <template #default="{ row }">
                      <div>
                        <el-button
                          v-if="row.status === 10"
                          type="success"
                          size="small"
                          @click="confirmOrder(row)"
                        >
                          确认
                        </el-button>
                      </div>
                    </template>
                  </el-table-column>
                </ElTable>
              </div>
              <ElPagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[100, 200, 300, 400, 500]"
                background
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                style="margin: 10px auto 0; text-align: right"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              ></ElPagination>
            </div>
          </template>
          <template #bottom>
            <el-tabs v-model="tabsValue" @tab-click="tabsClick">
              <el-tab-pane name="0" label="对账单详情">
                <el-form :model="detailForm" inline>
                  <el-form-item label="生产单号">
                    <el-input
                      v-model="detailForm.subOrderNumber"
                      placeholder="请输入订单号"
                      clearable
                      style="width: 130px"
                    />
                  </el-form-item>

                  <el-form-item label="底胚Sku">
                    <el-input
                      v-model="detailForm.baseSku"
                      placeholder="请输入底胚Sku"
                      clearable
                      style="width: 130px"
                    />
                  </el-form-item>
                  <el-form-item label="工艺编码">
                    <el-input
                      v-model="detailForm.craftCode"
                      placeholder="请输入工艺编码"
                      clearable
                      style="width: 130px"
                    />
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="searchDetail"
                      >查询
                    </el-button>
                  </el-form-item>
                  <el-form-item>
                    <el-button
                      v-if="[0, 1].some((id) => id === Number(nodeId))"
                      type="success"
                      @click="batchUpdate(detailSelections, 1)"
                      >批量编辑
                    </el-button>
                  </el-form-item>
                </el-form>
                <div class="table-wrap">
                  <ElTable
                    ref="deTableRef"
                    :data="detailList"
                    height="100%"
                    border
                    row-key="id"
                    @selection-change="handleDetailSelectionChange"
                  >
                    <el-table-column
                      show-overflow-tooltip
                      label="商品图片"
                      width="100"
                      prop="variant_image"
                      align="center"
                    >
                      <template #default="{ row }">
                        <el-image
                          v-if="row.variant_image"
                          preview-teleported
                          style="width: 60px; height: 60px"
                          :preview-src-list="[row.variant_image]"
                          :src="row.variant_image"
                        ></el-image>
                      </template>
                    </el-table-column>
                    <el-table-column
                      type="selection"
                      width="50"
                      header-align="center"
                      align="center"
                      fixed
                    />
                    <ElTableColumn
                      show-overflow-tooltip
                      width="60"
                      align="center"
                      label="序号"
                      type="index"
                      fixed
                    />
                    <el-table-column
                      label="生产单号"
                      prop="sub_order_number"
                      header-align="center"
                      align="center"
                      min-width="220"
                      show-overflow-tooltip
                    />
                    <el-table-column
                      label="第三方生产单号"
                      prop="product.factory_sub_order_number"
                      header-align="center"
                      align="center"
                      min-width="160"
                      show-overflow-tooltip
                    />
                    <el-table-column
                      show-overflow-tooltip
                      label="底胚SKU"
                      align="center"
                      width="150"
                      prop="product.base_sku"
                    />
                    <el-table-column
                      show-overflow-tooltip
                      label="变体SKU"
                      align="center"
                      width="150"
                      prop="product.variant_sku"
                    />
                    <el-table-column
                      label="商品名"
                      prop="product.product_name"
                      header-align="center"
                      align="center"
                      width="180"
                      show-overflow-tooltip
                    />
                    <el-table-column
                      show-overflow-tooltip
                      label="工艺编码"
                      width="100"
                      align="center"
                      prop="product.craft_code"
                    ></el-table-column>
                    <el-table-column
                      show-overflow-tooltip
                      label="工艺名称"
                      width="140"
                      align="center"
                      prop="product.craft_name"
                    ></el-table-column>
                    <el-table-column
                      show-overflow-tooltip
                      label="已发货数量"
                      width="100"
                      align="center"
                      prop="shipment_num"
                    ></el-table-column>
                    <el-table-column
                      show-overflow-tooltip
                      label="产品价格($)"
                      width="100"
                      align="center"
                      prop="product_price"
                    >
                      <template #default="{ row }">
                        <span>{{
                          row.template_price + row.craft_price || 0
                        }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column
                      show-overflow-tooltip
                      label="底胚价格($)"
                      width="100"
                      align="center"
                      prop="template_price"
                    ></el-table-column>
                    <el-table-column
                      show-overflow-tooltip
                      label="工艺价格($)"
                      width="100"
                      align="center"
                      prop="craft_price"
                    ></el-table-column>
                    <el-table-column
                      label="工厂"
                      prop="product.factory_code"
                      header-align="center"
                      align="center"
                      min-width="100"
                      show-overflow-tooltip
                    />
                    <el-table-column
                      label="备注"
                      prop="product.remark"
                      header-align="center"
                      align="center"
                      min-width="160"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="创建时间"
                      prop="product.create_time"
                      header-align="center"
                      align="center"
                      min-width="180"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      v-if="[0, 1].includes(nodeId)"
                      show-overflow-tooltip
                      align="center"
                      fixed="right"
                      header-align="center"
                      label="操作"
                      width="60"
                    >
                      <template #default="{ row }">
                        <div class="flex items-center justify-center gap-2">
                          <img
                            src="@/assets/images/edit.png"
                            width="24"
                            title="编辑"
                            style="cursor: pointer"
                            @click="batchUpdate([row], 1)"
                          />
                        </div>
                      </template>
                    </el-table-column>
                  </ElTable>
                </div>

                <ElPagination
                  v-model:current-page="detailPager.page"
                  v-model:page-size="detailPager.rows"
                  :page-sizes="[100, 200, 300, 400, 500]"
                  background
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="detailPager.total"
                  style="margin: 10px auto 0; text-align: right"
                  @size-change="handleDetailSizeChange"
                  @current-change="handleDetailCurrentChange"
                ></ElPagination>
              </el-tab-pane>
              <el-tab-pane name="1" label="订单详情">
                <el-form :model="orderForm" inline>
                  <el-form-item label="订单号">
                    <el-input
                      v-model="orderForm.orderNumber"
                      placeholder="请输入订单号"
                      clearable
                      style="width: 130px"
                    />
                  </el-form-item>
                  <el-form-item label="生产单号">
                    <el-input
                      v-model="orderForm.subOrderNumber"
                      placeholder="请输入订单号"
                      clearable
                      style="width: 130px"
                    />
                  </el-form-item>

                  <el-form-item>
                    <el-button type="primary" @click="getUsOrderList"
                      >查询
                    </el-button>
                  </el-form-item>
                  <el-form-item>
                    <el-button
                      v-if="[0, 1].some((id) => id === Number(nodeId))"
                      type="success"
                      @click="batchUpdate(orderSelections, 2)"
                      >批量编辑
                    </el-button>
                  </el-form-item>
                  <el-form-item>
                    <el-button
                      v-if="[0, 1].some((id) => id === Number(nodeId))"
                      type="primary"
                      @click="priceModification"
                      >修改物流价格
                    </el-button>
                  </el-form-item>
                </el-form>
                <div class="table-wrap">
                  <ElTable
                    ref="deTableRef"
                    :data="orderList"
                    height="100%"
                    border
                    row-key="id"
                    @selection-change="handleOrderSelectionChange"
                  >
                    <el-table-column
                      type="selection"
                      width="50"
                      header-align="center"
                      align="center"
                      fixed
                    />
                    <ElTableColumn
                      show-overflow-tooltip
                      width="60"
                      align="center"
                      label="序号"
                      type="index"
                      fixed
                    />
                    <el-table-column
                      label="订单号"
                      prop="order.order_number"
                      header-align="center"
                      align="center"
                      min-width="220"
                      show-overflow-tooltip
                    >
                      <template #default="{ row }">
                        <span>{{
                          row.erp_order_number || row.factory_order_number
                        }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column
                      label="店铺单号"
                      prop="order.shop_number"
                      header-align="center"
                      align="center"
                      min-width="160"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="客户"
                      prop="order.user_mark"
                      header-align="center"
                      align="center"
                      min-width="80"
                      show-overflow-tooltip
                    ></el-table-column>

                    <el-table-column
                      label="发货数(件)"
                      prop="order.product_num"
                      header-align="center"
                      align="center"
                      min-width="100"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="产品总价格($)"
                      prop="order.product_amount"
                      header-align="center"
                      align="center"
                      min-width="120"
                      show-overflow-tooltip
                    />
                    <el-table-column
                      label="底胚总价($)"
                      prop="template_total_price"
                      header-align="center"
                      align="center"
                      min-width="120"
                      show-overflow-tooltip
                    />
                    <el-table-column
                      label="工艺总价($)"
                      prop="craft_total_price"
                      header-align="center"
                      align="center"
                      min-width="120"
                      show-overflow-tooltip
                    />
                    <el-table-column
                      label="商品总价($)"
                      prop="product_total_amount"
                      header-align="center"
                      align="center"
                      min-width="120"
                      show-overflow-tooltip
                    />
                    <el-table-column
                      label="运费($)"
                      prop="order.pay_freight"
                      header-align="center"
                      align="center"
                      min-width="120"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="物流总价($)"
                      prop="carriage_total_amount"
                      header-align="center"
                      align="center"
                      min-width="120"
                      show-overflow-tooltip
                    />
                    <el-table-column
                      label="实付金额($)"
                      prop="order.actual_amount"
                      header-align="center"
                      align="center"
                      min-width="120"
                      show-overflow-tooltip
                    />
                    <el-table-column
                      label="完成时间"
                      prop="order.finish_time"
                      header-align="center"
                      align="center"
                      min-width="160"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="订单来源"
                      prop="order.namespace"
                      header-align="center"
                      align="center"
                      min-width="160"
                      show-overflow-tooltip
                    ></el-table-column>

                    <el-table-column
                      label="重量"
                      prop="order.weight"
                      header-align="center"
                      align="center"
                      min-width="160"
                      show-overflow-tooltip
                    ></el-table-column>

                    <el-table-column
                      label="商品备注"
                      prop="order.remark"
                      header-align="center"
                      align="center"
                      min-width="160"
                      show-overflow-tooltip
                    ></el-table-column>

                    <el-table-column
                      label="送货方式"
                      header-align="center"
                      align="center"
                      min-width="160"
                      show-overflow-tooltip
                    >
                      <template #default="{ row }">
                        <span v-if="row.order">{{
                          row.order.shipment_type == 1 ? '工厂物流' : '自我物流'
                        }}</span>
                      </template>
                    </el-table-column>

                    <el-table-column
                      label="物流名称"
                      prop="order.logistics_way_name"
                      header-align="center"
                      align="center"
                      min-width="160"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="揽收-姓名"
                      prop="order.receiver_name"
                      header-align="center"
                      align="center"
                      min-width="160"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="揽收-电话"
                      prop="order.receiver_phone"
                      header-align="center"
                      align="center"
                      min-width="160"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="揽收-国家"
                      prop="order.receiver_country"
                      header-align="center"
                      align="center"
                      min-width="160"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="揽收-省/州"
                      prop="order.receiver_province"
                      header-align="center"
                      align="center"
                      min-width="160"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="揽收-邮政编码"
                      prop="order.receiver_post_code"
                      header-align="center"
                      align="center"
                      min-width="160"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="创建时间"
                      prop="order.create_time"
                      header-align="center"
                      align="center"
                      min-width="180"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      v-if="[0, 1].includes(nodeId)"
                      show-overflow-tooltip
                      align="center"
                      fixed="right"
                      header-align="center"
                      label="操作"
                      width="120"
                    >
                      <template #default="{ row }">
                        <div
                          style="gap: 5px"
                          class="flex items-center justify-center flex-gap-5"
                        >
                          <img
                            @click="batchUpdate([row], 2)"
                            src="@/assets/images/edit.png"
                            width="24"
                            title="编辑"
                            style="cursor: pointer"
                          />
                          <img
                            @click="handleDelete(row.id)"
                            src="@/assets/images/delete.png"
                            width="24"
                            title="删除"
                            style="cursor: pointer"
                          />
                          <img
                            @click="getDetails(row)"
                            src="@/assets/images/view.png"
                            width="24"
                            title="查看详情"
                            style="cursor: pointer"
                          />
                        </div>
                      </template>
                    </el-table-column>
                  </ElTable>
                </div>

                <ElPagination
                  v-model:current-page="orderPager.page"
                  v-model:page-size="orderPager.rows"
                  :page-sizes="[100, 200, 300, 400, 500]"
                  background
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="orderPager.total"
                  style="margin: 10px auto 0; text-align: right"
                  @size-change="handleOrderSizeChange"
                  @current-change="handleOrderCurrentChange"
                ></ElPagination>
              </el-tab-pane>
              <el-tab-pane name="2" label="操作日志">
                <ul
                  style="
                    color: #333;
                    font-size: 12px;
                    height: 100%;
                    overflow: auto;
                  "
                >
                  <li
                    v-for="(item, index) in logList"
                    :key="index"
                    style="display: flex"
                  >
                    <span style="display: inline-block">
                      {{ item.create_time }}
                    </span>
                    <span style="margin: 0 5px 0 20px">{{
                      item.employee_account
                    }}</span>
                    <span style="display: inline-block">{{
                      item.description
                    }}</span>
                  </li>
                </ul>
              </el-tab-pane>
            </el-tabs>
          </template>
        </splitDiv>
      </div>
    </div>
  </div>
  <DetailView
    :order-id="safeOrderId"
    :dialog-visible="detailDialogVisible"
    @close="detailDialogVisible = false"
    @update="detailDialogVisible = $event"
  />
  <ElDialog
    v-model="confirmOrderVisible"
    title="确认对账单"
    width="70%"
    :close-on-click-modal="false"
  >
    <el-row>
      <el-col :span="6"> 对账单号：{{ currentRow?.rec_number }}</el-col>
      <el-col :span="12">
        账期(发货时间)： {{ currentRow?.start_time }} -
        {{ currentRow?.end_time }}
      </el-col>
      <el-col :span="6">
        成本总价($)： {{ currentRow?.product_total_amount }}
      </el-col>
    </el-row>
    <el-row style="margin: 10px 0">
      <el-col :span="6">
        工艺总价($)：{{ currentRow?.craft_total_amount }}
      </el-col>
      <el-col :span="6">
        物流总价($)： {{ currentRow?.carriage_total_amount }}
      </el-col>
      <el-col :span="6"> 应付金额($)：{{ currentRow?.total_amount }}</el-col>
      <el-col :span="6"> 实付金额($)：{{ currentRow?.actual_amount }}</el-col>
    </el-row>
    <el-row style="margin: 10px 0">
      <el-col v-if="currentRow?.water_list" :span="6">
        水单：
        <span
          v-for="item in (typeof currentRow?.water_list === 'string'
            ? currentRow.water_list
            : ''
          ).split(',')"
          :key="item"
          style="width: 30px"
        >
          <ImageView :src="item" />
        </span>
      </el-col>
      <el-col :span="6"> 总发货(件)： {{ currentRow?.num }}</el-col>
      <el-col :span="6"> 创建时间： {{ currentRow?.create_time }}</el-col>
    </el-row>
    <div></div>
    <ElForm ref="auditFormRef" :model="auditForm" label-width="80px">
      <ElFormItem label="驳回原因" prop="description">
        <ElInput v-model="auditForm.description" type="textarea" />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <span class="dialog-footer">
        <!-- <el-button @click="confirmOrderVisible = false">取消</el-button> -->
        <el-button type="success" @click="submitConfirmOrder(1)"
          >确认</el-button
        >
        <el-button type="danger" @click="submitConfirmOrder(2)">驳回</el-button>
      </span>
    </template>
  </ElDialog>
  <el-dialog
    v-model="processPriceDialogVisible"
    title="修改工艺价格"
    width="50%"
    :close-on-click-modal="false"
  >
    <el-table :data="craftPriceList" border style="width: 100%" height="330px">
      <el-table-column
        prop="process"
        label="工艺简称"
        width="260"
        align="center"
      />
      <el-table-column prop="base_price" label="基础价格($)" align="center">
        <template #default="scope">
          <el-input
            v-model="scope.row.base_price"
            placeholder="请输入基础价格"
            clearable
            oninput="value=value.replace(/[^\-?\d.]/g,'')"
            style="width: 100%"
          />
        </template>
      </el-table-column>
      <el-table-column prop="add_price" label="加价($)" align="center">
        <template #default="scope">
          <el-input
            v-model="scope.row.add_price"
            placeholder="请输入加价"
            clearable
            oninput="value=value.replace(/[^\-?\d.]/g,'')"
            style="width: 100%"
          />
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <el-button @click="processPriceDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitPodPrice">确定</el-button>
    </template>
  </el-dialog>
  <el-dialog v-model="batchUpdateVisible" width="1400px" title="批量编辑">
    <edit-order :list="updateProductList" />
    <template #footer>
      <el-button @click="batchUpdateVisible = false">取消</el-button>
      <el-button type="primary" @click="batchSave">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import DetailView from './detail.vue'
import EditOrder from './editOrder.vue'
import { ElMessage, ElTable, ElTree, TableColumnCtx } from 'element-plus'
import splitDiv from '@/components/splitDiv/splitDiv.vue'
import usePageList from '@/utils/hooks/usePageList'
import { useValue } from '@/utils/hooks/useValue'
import BigNumber from 'bignumber.js'
import {
  auditOrderApi,
  confirmPodOrderApi,
  apiRejectionOfReview,
  apiSetCraftData,
  podUsReconciliation,
  podUsReconciliationList,
  exportPodUsExcelApi,
  getPodUsShipmentDetailsById,
  getPodUsLogListApi,
  getPodShipmentGetById,
  confirmPodUsOrderApi,
  updatePodUsCarriageAmount,
  getReconciliationById,
  batchUpdatePrice,
  delPodUsOrderData,
} from '@/api/order'

import { nextTick, onMounted, ref, watch } from 'vue'
import 'element-plus/dist/index.css'
import {
  AccountStatementNote,
  AccountStatementNoteSearchForm,
  CountStatus,
  OrderDetails,
  ProductDetails,
} from '@/types/api/billOrder'
import { DetailForm, LogListData, IUpdatePrice } from '@/types/api/deliveryNote'
import ImageView from '@/components/ImageView.vue'

interface Tree {
  remark?: string
  count?: number
  code?: number
  children?: Tree[]
}

interface SummaryMethodProps<T = AccountStatementNote> {
  columns: TableColumnCtx<T>[]
  data: T[]
}

const updateProductList = ref<ProductDetails[]>([])
const batchUpdateVisible = ref(false)
const detailDialogVisible = ref(false)
const safeOrderId = ref()
const logList = ref<LogListData[]>([])
// const nameSpaceList = ref<string[]>([])
const treeData = ref<CountStatus[]>()
const [searchForm, resetSearchForm] = useValue<AccountStatementNoteSearchForm>(
  {},
)
const dateRange = ref<string[]>([])
const selections = ref<AccountStatementNote[]>([])
const detailSelections = ref<ProductDetails[]>([])
const orderSelections = ref<OrderDetails[]>([])
const detailList = ref<ProductDetails[]>([])
const orderList = ref<OrderDetails[]>([])
const tabsValue = ref<string>('0')
const singleTableRef = ref<InstanceType<typeof ElTable>>()
const currentRow = ref<AccountStatementNote | null>(null)

const batchSave = async () => {
  for (const item of updateProductList.value) {
    if (!item.craft_price && item.craft_price !== 0)
      return ElMessage.warning('请输入工艺价格')
    if (!item.template_price && item.craft_price !== 0)
      return ElMessage.warning('请输入模板价格')
  }
  await batchUpdatePrice({
    info_id: currentRow.value?.id,
    itemList: updateProductList.value.map((el: ProductDetails) => {
      return {
        id: el.id,
        craft_price: el.craft_price,
        template_price: el.template_price,
      }
    }),
  })
  ElMessage.success('保存成功')
  search()
  batchUpdateVisible.value = false
  await tabsClick()
}

const getDetails = async (row: OrderDetails) => {
  console.log(row)
  safeOrderId.value = row.order?.id
  detailDialogVisible.value = true
}

const batchUpdate = async (
  arr: ProductDetails[] | OrderDetails[],
  type: 1 | 2,
) => {
  if (!arr.length) return ElMessage.warning('请选择数据')
  if (type === 1) {
    updateProductList.value = JSON.parse(JSON.stringify(arr))
  } else if (type === 2) {
    const { data } = await getReconciliationById({
      ids: arr.map((el) => el.id).join(','),
    })
    updateProductList.value = data
  }
  batchUpdateVisible.value = true
}
const getSelectionsProperty = (property: keyof AccountStatementNote) => {
  return selections.value
    .map((el: AccountStatementNote) => el[property])
    .join(',')
}

const handleDetailSizeChange = (size: number) => {
  detailPager.value.rows = size
  searchDetail()
}

const handleDetailCurrentChange = (size: number) => {
  detailPager.value.page = size
  searchDetail()
}

const handleOrderSizeChange = (size: number) => {
  orderPager.value.rows = size
  getUsOrderList()
}

const handleOrderCurrentChange = (size: number) => {
  orderPager.value.page = size
  getUsOrderList()
}
const nodeId = ref<number>(0)
const treeRef = ref<InstanceType<typeof ElTree>>()
const {
  currentPage,
  pageSize,
  total,
  data: tableData,
  refresh: search,
  onCurrentPageChange: handleCurrentChange,
  onPageSizeChange: handleSizeChange,
} = usePageList({
  query: (page, pageSize) =>
    podUsReconciliationList(
      {
        ...searchForm.value,
        status: nodeId.value === -1 ? null : nodeId.value,
        startTime: dateRange.value && dateRange.value[0],
        endTime: dateRange.value && dateRange.value[1],
      },
      page,
      pageSize,
    ).then((res) => res.data),
})
watch(
  () => tableData.value,
  () => {
    ;(tableData.value as AccountStatementNote[]).forEach((item) => {
      item.total_amount = computedPrice(item)
    })
  },
  { immediate: true, deep: true },
)
const reset = () => {
  dateRange.value = []
  resetSearchForm()
}
const priceModification = () => {
  if (orderSelections.value.length === 0) {
    ElMessage.warning('至少选择一条对账单')
    return
  }
  ElMessageBox.prompt('修改物流价格', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /\d+/,
    inputErrorMessage: '请输入数字',
  }).then(async ({ value }: { value: string }) => {
    const price = parseFloat(value)
    if (isNaN(price) || price < 0) {
      ElMessage.error('价格必须为大于等于0的数字')
      return
    }
    await updatePodUsCarriageAmount({
      ids: orderSelections.value.map((item: OrderDetails) => item.id),
      carriage_amount: price,
    })
    ElMessage.success('操作成功')
    orderSelections.value = []
    search()
    await getUsOrderList()
  })
}
const getTreeNum = async () => {
  try {
    const res = await podUsReconciliation()
    treeData.value = res.data
    await nextTick(() => {
      treeRef.value!.setCurrentKey(nodeId.value, true)
    })
  } catch (e) {
    console.error(e)
  }
}
const rowClick = (row: AccountStatementNote) => {
  if (!row) {
    currentRow.value = null
  }
  currentRow.value = row
  tabsClick()
}

const tabsClick = async () => {
  if (!currentRow.value) {
    detailList.value = []
    logList.value = []
    return
  }
  await nextTick()
  if (tabsValue.value === '1') {
    await getUsOrderList()
  } else if (tabsValue.value === '2') {
    await getLogList()
  } else if (tabsValue.value === '0') {
    await searchDetail()
  }
}

// 删除
const handleDelete = async (id: string) => {
  await ElMessageBox.confirm('确定要删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  await delPodUsOrderData([id])
  ElMessage.success('删除成功')
  await getTreeNum()
  search()
}

const computedPrice = (row: AccountStatementNote) => {
  return new BigNumber(row.product_total_amount || 0)
    .plus(new BigNumber(row.carriage_total_amount || 0))
    .plus(new BigNumber(row.craft_total_amount || 0))
    .toString()
}
const craftPriceList = ref<IUpdatePrice[]>([])
const processPriceDialogVisible = ref(false)

const submitPodPrice = async () => {
  const filteredList = craftPriceList.value.filter(
    (item: IUpdatePrice) => item.base_price && item.add_price,
  )
  if (filteredList.length > 0) {
    try {
      const res = await apiSetCraftData({
        id: currentRow.value?.id,
        craftTotalPrice: currentRow.value?.craft_total_amount,
        recNumber: currentRow.value?.rec_number,
        craftPriceList: filteredList,
      })
      if (res.code !== 200) return
      ElMessage.success('修改成功')
      processPriceDialogVisible.value = false
      search()
      await getTreeNum()
    } catch (error) {
      console.error(error)
    }
  } else {
    ElMessage.error('至少提交一条数据')
  }
}

const handleSelectionChange = (v: AccountStatementNote[]) => {
  selections.value = v
}

const handleDetailSelectionChange = (v: ProductDetails[]) => {
  detailSelections.value = v
}

const handleOrderSelectionChange = (v: OrderDetails[]) => {
  orderSelections.value = v
}
const getSummaries = (param: SummaryMethodProps) => {
  const { columns, data } = param
  const sums: string[] = []
  columns.forEach(
    (column: TableColumnCtx<AccountStatementNote>, index: number) => {
      if (index === 0) {
        sums[index] = '合计'
        return
      }
      const values = data.map((item: AccountStatementNote) => {
        return Number(item[column.property as keyof AccountStatementNote])
      })
      if (!values.every((value: number) => !isNaN(value))) {
        return
      }
      sums[index] = values
        .reduce((prev: BigNumber, curr: number) => {
          const value = new BigNumber(curr)
          return prev.plus(value) // 直接处理 BigNumber 类型
        }, new BigNumber(0))
        .toString()
    },
  )

  return sums
}
const confirmOrderVisible = ref<boolean>(false)
const auditForm = ref({
  description: '',
})
const auditFormRef = ref()
const auditOrder = (key: string) => {
  let url = ''
  let text = ''
  switch (key) {
    case 'pay':
      url = 'pod/podReconciliation/payment'
      text = '确认付款'
      break
    case 'archive':
      url = 'pod/podReconciliation/archiving'
      text = '确认归档'
      break
  }

  if (selections.value.length === 0) {
    return ElMessage.warning('请选择要操作的数据')
  }
  ElMessageBox.confirm(`${text}对账单？`, '重要提示', {
    confirmButtonText: '确定',
    type: 'warning',
  }).then(async () => {
    const ids = selections.value
      .map((el: AccountStatementNote) => el.id)
      .join(',')
    await auditOrderApi(url, ids)
    ElMessage.success('操作成功')
    search()
    await getTreeNum()
  })
}
const rejectOrder = () => {
  if (selections.value.length === 0) {
    return ElMessage.warning('请选择要操作的数据')
  }
  ElMessageBox.prompt('请输入驳回原因', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    inputPattern: /.+/,
    customClass: 'reject',
    inputErrorMessage: '请输入驳回原因',
    inputPlaceholder: '驳回原因',
  }).then(async ({ value }: { value: string }) => {
    const ids = getSelectionsProperty('id')
    const recNumbers = getSelectionsProperty('rec_number')
    try {
      await apiRejectionOfReview({
        ids: ids,
        description: value,
        recNumbers: recNumbers,
      })
      ElMessage.success('操作成功')
      search()
      await getTreeNum()
    } catch (e) {
      console.error(e)
    }
  })
}
const confirmOrder = async (item: AccountStatementNote) => {
  currentRow.value = item
  confirmOrderVisible.value = true
}

interface ConfirmOrderPayload {
  ids: string
  description?: string
  pass?: number
}

const submitConfirmOrder = async (type: number) => {
  // const ids = selections.value
  //   .map((el: AccountStatementNote) => el.id)
  //   .join(',')

  let apiPayload: ConfirmOrderPayload = { ids: `${currentRow.value?.id}` }

  if (type === 1) {
    // 确认操作
    await confirmPodUsOrderApi(apiPayload)
  } else {
    // 驳回操作
    try {
      await auditFormRef.value?.validate()
    } catch {
      return // 验证失败，终止操作
    }
    apiPayload = {
      ...apiPayload,
      description: auditForm.value.description,
      pass: 0,
    }
    await confirmPodOrderApi(apiPayload)
  }

  confirmOrderVisible.value = false
  ElMessage.success('操作成功')
  search()
  await getTreeNum()
  if (singleTableRef.value) {
    singleTableRef.value!.setCurrentRow(currentRow.value)
  }
}
watch(
  () => tableData.value,
  () => {
    if (tableData.value && tableData.value.length > 0) {
      if (singleTableRef.value) {
        singleTableRef.value!.setCurrentRow(tableData.value[0])
        currentRow.value = (tableData.value as never)[0]
      }
    } else {
      detailList.value = []
    }
  },
  { immediate: true },
)
const nodeClick = (data: Tree) => {
  nodeId.value = data.code || 0
  // if (data.code !== 0) {
  search()
  // }
}
const detailForm = ref({} as DetailForm)
const orderForm = ref({} as DetailForm)
const detailPager = ref({
  page: 1,
  rows: 100,
  total: 0,
})
const orderPager = ref({
  page: 1,
  rows: 100,
  total: 0,
})
const searchDetail = async () => {
  try {
    detailSelections.value = []
    const res = await getPodShipmentGetById({
      ...detailForm.value,
      // startTime: detailForm.value.dateRange && detailForm.value.dateRange[0],
      // endTime: detailForm.value.dateRange && detailForm.value.dateRange[1],
      currentPage: detailPager.value.page,
      pageSize: detailPager.value.rows,
      infoId: currentRow.value?.id,
    })
    detailList.value = res.data.records || []
    detailPager.value.total = res.data.total
  } catch (e) {
    console.error(e)
  }
}

const getUsOrderList = async () => {
  try {
    const res = await getPodUsShipmentDetailsById({
      ...orderForm.value,
      currentPage: orderPager.value.page,
      pageSize: orderPager.value.rows,
      infoId: currentRow.value?.id,
    })
    orderList.value = res.data.records || []
    orderPager.value.total = res.data.total
  } catch (e) {
    console.error(e)
  }
}
const getLogList = async () => {
  try {
    const res = await getPodUsLogListApi(currentRow.value?.id)
    logList.value = res.data
  } catch (e) {
    console.error(e)
  }
}
const exportExcel = async () => {
  if (selections.value.length !== 1) {
    return ElMessage.warning('请选择一条数据')
  }
  const ids = selections.value
    .map((el: AccountStatementNote) => el.id)
    .join(',')
  try {
    const res = await exportPodUsExcelApi(ids)
    window.open(res.data)
  } catch (e) {
    console.error(e)
  }
}
onMounted(() => {
  getTreeNum()
})
</script>

<style lang="scss" scoped>
.img-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.img-item {
  font-size: 28px;
  color: #8c939d;
  width: 58px;
  height: 58px;
  text-align: center;
  border: 1px solid #d9d9d9;
  cursor: pointer;
  position: relative;

  .close-bill {
    position: absolute;

    font-size: 14px;
    top: -8px;
    right: -8px;
    color: #666;
  }
}

.header-filter-form {
  :deep(.el-form-item) {
    margin-right: 14px;
    margin-bottom: 10px;
  }
}

$border: solid 1px #ddd;

.send-order-list {
  display: grid;
  grid-template-columns: 2fr 1fr;
  border-left: $border;
  border-top: $border;
}

.send-order-column {
  padding: 10px 16px;
  line-height: 1.5;
}

.send-order-header {
  font-weight: bold;
  text-align: center;
  background-color: #f8f8f9;
}

.send-order-product-item {
  display: flex;
  justify-content: space-between;
  gap: 20px;

  &:not(:first-child) {
    border-top: $border;
    padding: 10px 0;
  }

  .send-order-prop-list {
    flex: 1;
  }
}

.send-order-product-image {
  width: 100px;
}

.dialog-footer {
  display: flex;
  justify-content: center;
}

.delivery-note-list {
  :deep(.vertical-align-top) {
    vertical-align: top;
  }
}

.left {
  width: 160px;

  :deep(.el-tree-node__content) {
    height: 30px;
    line-height: 30px;
  }

  :deep(.el-tree-node__label) {
    font-size: 13px;
    cursor: pointer;
    display: inline-block;
    width: 100%;
    color: black !important;

    padding: 3px 7px;
  }

  :deep(.el-tree-node__expand-icon) {
    display: none;
  }

  :deep(.is-current) {
    .tree-node-label,
    .tree-node-count {
      background-color: #ecf5ff;
      color: #409eff !important;
    }

    .el-tree-node__children {
      .tree-node-label,
      .tree-node-count {
        background-color: transparent !important;
        color: black !important;
      }
    }
  }
}

.tree-node {
  display: flex;
  color: #333;
  font-weight: 500;
}

.right {
  flex: 1;
  flex-shrink: 0;
  background: white;
  overflow: hidden;
}

::v-deep(.el-tree-node__label) {
  font-size: 13px;
  color: rgb(96, 98, 102);
  cursor: pointer;
}

::v-deep(.el-tree-node__expand-icon) {
  display: none;
}

::v-deep(.el-tree-node__label) {
  display: inline-block;
  width: 100%;
  color: black !important;

  padding: 3px 7px;
}

::v-deep(.is-current) {
  .el-tree-node__label {
    background-color: #ecf5ff;
    color: #409eff !important;
  }

  .el-tree-node__children {
    .el-tree-node__label {
      background-color: transparent !important;
      color: black !important;
    }
  }
}

::v-deep(.splitpanes__pane) {
  display: flex;
  flex-direction: column;
}

::v-deep(.splitpanes--horizontal > .splitpanes__splitter) {
  min-height: 5px;
  margin-top: 10px;
}

.draw-line {
  width: 100%;
  height: 5px;
  background: #eff3f6;
}

.btn-list {
  margin-bottom: 10px;
}

::v-deep(.el-tree-node) {
  cursor: pointer;
  margin-bottom: 5px;
}

::v-deep(.el-tree-node__label) {
  font-size: 14px;
}

::v-deep(.el-tabs) {
  display: flex;
  // flex-direction: column;
  height: 100%;

  .el-tabs__content {
    flex: 1;
    flex-shrink: 0;
    overflow: hidden;

    .el-tab-pane {
      height: 100%;
      display: flex;
      flex-direction: column;
      overflow: hidden;
    }
  }
}

.delivery-note-page {
  :deep(#top) {
    height: 100%;
  }
}

::v-deep(.el-form--inline .el-form-item) {
  margin-right: 10px;
}
</style>
