<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.shipmentNumber"
                    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="num"
                    width="100"
                    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="craft_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"
                    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>
                      <div>
                        <el-button
                          v-if="row.status === 20"
                          type="success"
                          size="small"
                          @click="onPayment(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-date-picker
                      v-model="detailForm.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"
                    />
                  </el-form-item> -->
                  <el-form-item label="底胚">
                    <el-input
                      v-model="detailForm.baseSku"
                      placeholder="请输入底胚"
                      clearable
                      style="width: 130px"
                    />
                  </el-form-item>
                  <el-form-item label="工艺简称">
                    <el-input
                      v-model="detailForm.process"
                      placeholder="请输入工艺简称"
                      clearable
                      style="width: 130px"
                    />
                  </el-form-item>
                  <el-form-item label="供应货号">
                    <el-input
                      v-model="detailForm.supplierItemNo"
                      placeholder="请输入供应货号"
                      clearable
                      style="width: 130px"
                    />
                  </el-form-item>
                  <el-form-item label="发货单号">
                    <el-input
                      v-model="detailForm.shipmentNumber"
                      placeholder="请输入发货单号"
                      clearable
                      style="width: 130px"
                    />
                  </el-form-item>

                  <el-form-item label="订单号">
                    <el-input
                      v-model="detailForm.orderNumber"
                      placeholder="请输入订单号"
                      clearable
                      style="width: 130px"
                    />
                  </el-form-item>
                  <el-form-item label="生产单号">
                    <el-input
                      v-model="detailForm.subOrderNumber"
                      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="primary"
                      @click="priceModification(1)"
                      >修改成本价格
                    </el-button>
                  </el-form-item>
                  <el-form-item>
                    <el-button
                      v-if="[0, 1].some((id) => id === Number(nodeId))"
                      type="warning"
                      @click="modifyProcessPrices"
                      >修改工艺价格
                    </el-button>
                  </el-form-item>
                  <el-form-item>
                    <el-button
                      v-if="[0, 1].some((id) => id === Number(nodeId))"
                      type="primary"
                      @click="priceModification(4)"
                      >修改物流价格
                    </el-button>
                  </el-form-item>
                </el-form>
                <div class="table-wrap">
                  <ElTable
                    size="small"
                    :data="detailList"
                    height="100%"
                    border
                    @selection-change="handleDetailSelectionChange"
                  >
                    <el-table-column
                      type="selection"
                      width="50"
                      header-align="center"
                      align="center"
                    />
                    <ElTableColumn
                      show-overflow-tooltip
                      width="60"
                      align="center"
                      label="序号"
                      type="index"
                    />
                    <el-table-column
                      label="生产单号"
                      prop="factory_sub_order_number"
                      header-align="center"
                      align="center"
                      min-width="160"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="店铺单号"
                      prop="shop_number"
                      header-align="center"
                      align="center"
                      min-width="160"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="客户"
                      prop="user_mark"
                      header-align="center"
                      align="center"
                      min-width="80"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="订单号"
                      prop="factory_order_number"
                      header-align="center"
                      align="center"
                      min-width="130"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="底胚"
                      prop="base_sku"
                      header-align="center"
                      align="center"
                      min-width="150"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="发货数(件)"
                      prop="shipment_num"
                      header-align="center"
                      align="center"
                      min-width="100"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="成本单价(￥)"
                      prop="cost_price"
                      header-align="center"
                      align="center"
                      min-width="120"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="工艺简称"
                      prop="process"
                      header-align="center"
                      align="center"
                      min-width="90"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="设计面数"
                      prop="face_count"
                      header-align="center"
                      align="center"
                      min-width="90"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="工艺单价(￥)"
                      prop="craft_price"
                      header-align="center"
                      align="center"
                      min-width="120"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="物流价格(￥)"
                      prop="carriage_amount"
                      header-align="center"
                      align="center"
                      min-width="120"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="发货单号"
                      prop="shipment_number"
                      header-align="center"
                      align="center"
                      min-width="160"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="供应货号"
                      prop="supplier_item_no"
                      header-align="center"
                      align="center"
                      min-width="160"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="产品名称"
                      prop="product_name"
                      header-align="center"
                      align="center"
                      min-width="180"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="订单来源"
                      prop="namespace"
                      header-align="center"
                      align="center"
                      min-width="160"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="变体SKU"
                      prop="variant_sku"
                      header-align="center"
                      align="center"
                      min-width="160"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="工艺简称"
                      prop="process"
                      header-align="center"
                      align="center"
                      min-width="160"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="工艺全称"
                      prop="process_name"
                      header-align="center"
                      align="center"
                      min-width="160"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="重量"
                      prop="weight"
                      header-align="center"
                      align="center"
                      min-width="160"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="商品备注"
                      prop="remark"
                      header-align="center"
                      align="center"
                      min-width="160"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="模版类型"
                      header-align="center"
                      width="140"
                      align="center"
                      show-overflow-tooltip
                    >
                      <template #default="{ row }">
                        {{ row.diy_type == 0 ? '公模' : '私模' }}
                      </template>
                    </el-table-column>
                    <el-table-column
                      label="设计面数"
                      prop="face_count"
                      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 }">
                        {{ row.shipping_way == 1 ? '送货上门' : '快递' }}
                      </template>
                    </el-table-column>
                    <el-table-column
                      label="运费(￥)"
                      prop="carriage_amount"
                      header-align="center"
                      align="center"
                      min-width="160"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="物流名称"
                      prop="carriage_name"
                      header-align="center"
                      align="center"
                      min-width="160"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="物流跟踪号"
                      prop="logistics_tracking"
                      header-align="center"
                      align="center"
                      min-width="160"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="揽收-姓名"
                      prop="lanshou_name"
                      header-align="center"
                      align="center"
                      min-width="160"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="揽收-电话"
                      prop="lanshou_phone"
                      header-align="center"
                      align="center"
                      min-width="160"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="揽收-区域"
                      prop="lanshou_region"
                      header-align="center"
                      align="center"
                      min-width="160"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="揽收-地址"
                      prop="lanshou_address"
                      header-align="center"
                      align="center"
                      min-width="160"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="揽收-邮政编码"
                      prop="lanshou_post"
                      header-align="center"
                      align="center"
                      min-width="160"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      label="创建时间"
                      prop="create_time"
                      header-align="center"
                      align="center"
                      min-width="180"
                      show-overflow-tooltip
                    ></el-table-column>
                    <!-- <el-table-column
                      label="更新时间"
                      prop="update_time"
                      header-align="center"
                      align="center"
                      min-width="180"
                      show-overflow-tooltip
                    ></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="操作日志">
                <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.createTime }}
                    </span>
                    <span style="margin: 0 5px 0 20px">{{
                      item.employeeAccount
                    }}</span>
                    <span style="display: inline-block">{{
                      item.description
                    }}</span>
                  </li>
                </ul>
              </el-tab-pane>
            </el-tabs>
          </template>
        </splitDiv>
      </div>
    </div>
  </div>
  <!-- 付款 -->
  <el-dialog
    v-model="paymentDialogVisible"
    title="付款"
    width="30%"
    :close-on-click-modal="false"
  >
    <el-form ref="paymentFormRef" :model="paymentForm" label-width="100px">
      <el-form-item label="应付金额" prop="amount">
        <el-input
          v-model="paymentForm.payableAmount"
          placeholder="请输入付款金额"
          disabled
          clearable
        />
      </el-form-item>
      <el-form-item
        label="实付金额"
        prop="actualAmount"
        :rules="[
          {
            required: true,
            message: '请输入实付金额',
          },
          {
            type: 'number',
            message: '实付金额需要为数字',
          },
        ]"
      >
        <el-input
          v-model.number="paymentForm.actualAmount"
          placeholder="请输入实付金额"
          clearable
        />
      </el-form-item>
      <el-form-item
        label="水单"
        prop="waterList"
        :rules="[
          {
            required: true,
            message: '请上传水单',
            trigger: 'blur',
          },
        ]"
      >
        <div v-loading="uploadLoading" class="avatar-uploader-icon">
          <div class="img-list">
            <template v-if="paymentForm.waterList.length">
              <div
                v-for="(item, index) in paymentForm.waterList"
                :key="index"
                class="img-item"
              >
                <img :src="item.url" style="width: 100%; height: 100%" />
                <el-icon
                  v-if="paymentForm.waterList.length"
                  class="close-bill"
                  @click="paymentForm.waterList.splice(index, 1)"
                >
                  <CircleClose />
                </el-icon>
              </div>
            </template>
            <div class="img-item">
              <el-icon style="width: 100%; height: 100%" @click="toUpload">
                <Plus />
              </el-icon>
            </div>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="paymentDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handlePayment">确定</el-button>
    </template>
  </el-dialog>
  <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 :span="6" v-if="currentRow?.water_list">
        水单：
        <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"
        :rules="[{ required: true, message: '请输入驳回原因' }]"
      >
        <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>
</template>

<script setup lang="ts">
import { ElMessage, ElTable, ElTree, TableColumnCtx } from 'element-plus'
import splitDiv from '@/components/splitDiv/splitDiv.vue'
import { CircleClose, Plus } from '@element-plus/icons-vue'
// import pendingReconciliation from './pendingReconciliation.vue'
import usePageList from '@/utils/hooks/usePageList'
import { useValue } from '@/utils/hooks/useValue'
import BigNumber from 'bignumber.js'
import {
  apiBillPodPayment,
  auditOrderApi,
  confirmPodOrderApi,
  apiRejectionOfReview,
  exportPodExcelApi,
  getPodLogListApi,
  getPodShipmentDetailsById,
  podReconciliation,
  podReconciliationList,
  updateRecPrice,
  apiGetCraftGroup,
  apiSetCraftData,
} from '@/api/order'

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

// import { getUserMarkList } from '@/api/auth.ts'
interface Tree {
  remark?: string
  count?: number
  code?: number
  children?: Tree[]
}

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

interface PaymentForm {
  waterList: {
    url: string | undefined
  }[]
  id?: number | string
  actualAmount?: number | string
  payableAmount?: number | string
}

const logList = ref<LogListData[]>([])
// const nameSpaceList = ref<string[]>([])
const treeData = ref<CountStatus[]>()
const [searchForm, resetSearchForm] = useValue<AccountStatementNoteSearchForm>(
  {},
)

const paymentFormRef = ref()
const uploadLoading = ref(false)
const dateRange = ref<string[]>([])
const selections = ref<AccountStatementNote[]>([])
const detailSelections = ref<ItemList[]>([])
const detailList = ref<ItemList[]>([])
const tabsValue = ref<string>('0')
const singleTableRef = ref<InstanceType<typeof ElTable>>()
const currentRow = ref<AccountStatementNote | null>(null)

const paymentDialogVisible = ref(false)
const paymentForm = ref<PaymentForm>({
  waterList: [],
  id: '',
  actualAmount: '',
  payableAmount: '',
})
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 nodeId = ref<number | string>(0)
const treeRef = ref<InstanceType<typeof ElTree>>()
const {
  currentPage,
  pageSize,
  total,
  data: tableData,
  refresh: search,
  onCurrentPageChange: handleCurrentChange,
  onPageSizeChange: handleSizeChange,
} = usePageList({
  query: (page, pageSize) =>
    podReconciliationList(
      {
        ...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 = (type: 1 | 3 | 4) => {
  if (detailSelections.value.length === 0) {
    ElMessage.warning('至少选择一条对账单')
    return
  }
  const pricePrompts: Record<1 | 3 | 4, { title: string; param: string }> = {
    1: { title: '修改工厂价格', param: 'costPrice' },
    3: { title: '修改工艺价格', param: 'craftPrice' },
    4: { title: '修改物流价格', param: 'carriageAmount' },
  }
  const promptConfig = pricePrompts[type]
  if (!promptConfig) {
    ElMessage.error('无效的操作类型')
    return
  }
  ElMessageBox.prompt(promptConfig.title, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /\d+/,
    inputErrorMessage: '请输入数字',
  }).then(async ({ value }: { value: string }) => {
    const price = parseFloat(value)
    if (isNaN(price) || price < 0) {
      ElMessage.error('价格必须为大于等于0的数字')
      return
    }
    await updateRecPrice({
      ids: detailSelections.value.map((item: ItemList) => item.id).join(),
      ...{ [promptConfig.param]: price },
      infoId: currentRow.value?.id,
    })
    ElMessage.success('操作成功')
    detailSelections.value = []
    search()
    searchDetail()
  })
}
const onPayment = async (item: AccountStatementNote) => {
  currentRow.value = item
  paymentForm.value = {
    payableAmount: item.total_amount,
    actualAmount: '',
    waterList: [],
  }
  await nextTick()
  paymentFormRef.value && paymentFormRef.value.clearValidate()
  paymentDialogVisible.value = true
}
const handlePayment = async () => {
  try {
    await paymentFormRef.value?.validate()
  } catch {
    return
  }
  if (Number(paymentForm.value.actualAmount) <= 0) {
    return ElMessage.warning('实付金额需大于等于0')
  }
  await apiBillPodPayment({
    ...paymentForm.value,
    waterList: paymentForm.value.waterList
      .map((item: { url: string | undefined }) => item.url)
      .join(','),
    id: currentRow.value?.id,
    recNumber: currentRow.value?.rec_number,
  })
  ElMessage.success('付款成功')
  paymentDialogVisible.value = false
  search()
  await getTreeNum()
}

const handleWaterBill = async (e: Event) => {
  const files = (e.target as HTMLInputElement).files || []
  const request = []
  uploadLoading.value = true
  for (const file of files) {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('businessType', 'other')
    request.push(uploadImageApi(formData))
  }
  const resList = []
  try {
    const res = await Promise.all(request)
    for (const item of res) {
      const { filePath, code } = item
      if (code === 500) {
        ElMessageBox.alert('上传失败', '系统提示', { type: 'error' })
        return
      } else if (code === 404) {
        ElMessageBox.alert('接口异常', '系统提示', { type: 'error' })
        return
      } else if (code === 403) {
        ElMessageBox.alert('权限不足', '系统提示', { type: 'error' })
        return
      }
      resList.push({ url: filePath })
    }

    paymentForm.value.waterList = resList
  } catch (error) {
    console.log(error)
  } finally {
    uploadLoading.value = false
  }
}

const getTreeNum = async () => {
  try {
    const res = await podReconciliation()
    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 === '0') {
    await searchDetail()
  } else {
    await getLogList()
  }
}

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 modifyProcessPrices = async () => {
  const res = await apiGetCraftGroup(currentRow.value?.id)
  const result = (res.data as string[]).map((item) => ({
    process: item,
    base_price: '',
    add_price: '',
  }))
  craftPriceList.value = result || []
  processPriceDialogVisible.value = true
}
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 toUpload = () => {
  const input = document.createElement('input')
  input.style.display = 'none'
  input.type = 'file'
  input.multiple = true
  input?.click()
  input.onchange = function (e: Event) {
    handleWaterBill(e)
  }
}
const handleSelectionChange = (v: AccountStatementNote[]) => {
  selections.value = v
}

const handleDetailSelectionChange = (v: ItemList[]) => {
  detailSelections.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 confirmPodOrderApi(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 ?? ''
  // if (data.code !== 0) {
  search()
  // }
}
const detailForm = ref({} as DetailForm)
const detailPager = ref({
  page: 1,
  rows: 100,
  total: 0,
})
const searchDetail = async () => {
  try {
    const res = await getPodShipmentDetailsById({
      ...detailForm.value,
      // startTime: detailForm.value.dateRange && detailForm.value.dateRange[0],
      // endTime: detailForm.value.dateRange && detailForm.value.dateRange[1],
      page: detailPager.value.page,
      rows: detailPager.value.rows,
      infoId: currentRow.value?.id,
    })
    detailList.value = res.data.records || []
    detailPager.value.total = res.data.total
  } catch (e) {
    console.error(e)
  }
}
const getLogList = async () => {
  try {
    const res = await getPodLogListApi(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 exportPodExcelApi(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>
