<template>
  <div class="w-[100vw] bg-white page-cargo-consolidation">
    <div
      v-loading="loading"
      class="w-[100%] min-h-[100vh]"
    >
      <el-form
        style="width: 100%"
        inline
        :loading="loading"
        @submit.prevent="getList"
      >
        <el-form-item
          label="ETD Range"
          style="margin-bottom: 10px"
        >
          <el-date-picker
            size="small"
            v-model="dateRange"
            type="daterange"
            unlink-panels
            clearable
            start-placeholder="Start date"
            end-placeholder="End date"
            :shortcuts="dateShortcuts"
          />
        </el-form-item>
        <el-form-item style="margin-bottom: 10px">
          <el-tooltip content="时间范围最好不要选太大, 不然数据太多会卡">
            <el-button
              class="custom-button"
              @click="getList"
            >
              Search
            </el-button>
          </el-tooltip>
          <el-button
            @click="openTempShip"
            size="small"
          >
            候选货物列表
          </el-button>
        </el-form-item>
      </el-form>

      <el-tabs v-model="currentTab">
        <el-tab-pane
          v-for="tab in finalTabs"
          :key="tab.value"
          :label="tab.label"
          :name="tab.value"
        ></el-tab-pane>
      </el-tabs>
      <el-table
        border
        :header-cell-style="{ backgroundColor: 'rgb(227, 241, 253)' }"
        :data="computedList"
        highlight-current-row
        style="width: 100%"
        max-height="330"
        @row-click="($e) => getSubList($e)"
      >
        <el-table-column
          prop="Name"
          label="船名&航次"
          min-width="500"
        />
        <el-table-column
          prop="Forwarder"
          label="货代"
          width="100"
        />
        <el-table-column
          prop="ETD"
          label="ETD"
          width="100"
        />
        <el-table-column
          prop="ATD"
          label="ATD"
          width="100"
        />
        <el-table-column
          prop="ETA"
          label="ETA"
          width="100"
        />
        <el-table-column
          prop="ATA"
          label="ATA"
          width="100"
        />
        <el-table-column
          prop="Cut_Off_Date"
          label="入仓时间"
          width="100"
        />
        <el-table-column
          label="截止时间"
          width="200"
        >
          <template #default="scope">
            <div>
              {{ formatCutOffDateTime(scope.row.Cut_Off_Date_Time) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="Status"
          label="状态"
          width="75"
        />
        <el-table-column
          prop="GRN"
          label="入仓单号"
          min-width="200"
        />
        <el-table-column
          prop="Booking_Number"
          label="订舱号"
          min-width="120"
        />
        <el-table-column
          prop="Container_Number"
          label="柜号"
          min-width="125"
        />
        <el-table-column
          prop="Carrier"
          label="船东"
          min-width="100"
        />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              size="small"
              type="warning"
              link
              :disabled="!scope.row.SubscriptionId"
              @click="openMapDrawer(scope.row)"
            >
              查看轨迹
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div
        v-show="currentRow.Name?.length"
        class="flex justify-between mt-8"
      >
        <div class="flex">
          <div class="flex flex-wrap min-w-[800px] mr-2">
            <el-input
              v-if="currentTab === 'Arrangement' && superUserIDList.includes(currentUser)"
              :disabled="!['Arrangement', 'my_request'].includes(currentTab)"
              style="width: 200px; height: 24px; margin-right: 10px"
              size="small"
              v-model="bookingNumber"
            >
              <template #append>
                <el-button
                  class="custom-button"
                  size="small"
                  style="padding-top: 0; padding-bottom: 0"
                  @click="updateBookingNumber"
                >
                  更新订舱号
                </el-button>
              </template>
            </el-input>
            <el-input
              v-if="currentTab === 'Arrangement' && superUserIDList.includes(currentUser)"
              :disabled="!['Arrangement', 'my_request'].includes(currentTab)"
              style="width: 200px; height: 24px; margin-right: 10px"
              size="small"
              v-model="containerNumber"
            >
              <template #append>
                <el-button
                  class="custom-button"
                  size="small"
                  style="padding-top: 0; padding-bottom: 0"
                  @click="updateContainerNumber"
                >
                  更新柜号
                </el-button>
              </template>
            </el-input>
            <el-button
              v-if="
                currentTab === 'Arrangement' &&
                ['可用', '已截仓'].includes(currentRow.Status) &&
                superUserIDList.includes(currentUser)
              "
              size="small"
              type="danger"
              @click="updateStatus('已确认')"
            >
              确认集货
            </el-button>
            <el-button
              v-if="
                currentTab === 'Arrangement' &&
                ['已确认'].includes(currentRow.Status) &&
                superUserIDList.includes(currentUser)
              "
              size="small"
              type="danger"
              @click="updateStatus('可用')"
            >
              恢复航次
            </el-button>
            <el-button
              class="custom-button"
              v-if="
                ['Arrangement', 'my_request'].includes(currentTab) &&
                ['可用'].includes(currentRow.Status)
              "
              size="small"
              @click="addBulkProduct"
            >
              提交大货集货申请
            </el-button>
            <el-button
              class="custom-button"
              v-if="
                ['Arrangement', 'my_request'].includes(currentTab) &&
                ['可用'].includes(currentRow.Status)
              "
              size="small"
              @click="addSample"
            >
              提交样品集货申请
            </el-button>
            <el-button
              v-if="['Arrangement', 'my_request'].includes(currentTab)"
              :disabled="subList.length < 1"
              size="small"
              type="danger"
              @click="generateSubList"
            >
              放弃下方表格改动
            </el-button>
            <el-button
              class="custom-button"
              size="small"
              :disabled="subList.length < 1"
              @click="exportSubTable(subList, currentRow.Name)"
            >
              导出Excel文档
            </el-button>
            <el-button
              v-if="
                ['Arrangement'].includes(currentTab) ||
                (['可用'].includes(currentRow.Status) && ['my_request'].includes(currentTab))
              "
              :disabled="subList.length < 1"
              size="small"
              type="primary"
              class="custom-button small"
              @click="commitWithSDK"
            >
              保存更改
            </el-button>
          </div>
        </div>
        <div>
          <div class="flex justify-end min-w-[380px] gap-2">
            <div class="flex">总重量: {{ computedWeight }}</div>
            <div class="flex">总体积: {{ computedCube }}</div>
            <div class="flex">总离岸价: {{ computedTotalFOB }}</div>
          </div>
          <div class="flex justify-end min-w-[380px] gap-2">
            <div class="flex">已选重量: {{ computedSelectedWeight }}</div>
            <div class="flex">已选体积: {{ computedSelectedCube }}</div>
            <div class="flex">已选离岸价: {{ computedSelectedTotalFOB }}</div>
          </div>
        </div>
      </div>
      <el-table
        class="mt-4"
        size="small"
        :data="subList"
        style="width: 100%"
        :row-style="calcRowStyle"
        :header-cell-style="{ backgroundColor: 'rgb(227, 241, 253)' }"
        :empty-text="
          currentRow.Name?.length ? '暂无数据' : '请点击voyage表格其中一行以查询相应记录'
        "
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column
          fixed
          type="index"
          width="40"
        ></el-table-column>
        <el-table-column
          :sortable="currentTab === 'Arrangement'"
          :sort-method="batchRecordSort"
          fixed
          label="CRM批次记录"
          width="220"
        >
          <template #default="scope">
            <el-select
              v-model="scope.row.batchRecord"
              size="small"
              :remote-method="debounce(search, 1500)"
              remote
              style="width: 100%"
              :loading="loading2"
              filterable
              clearable
              :placeholder="scope.row.Sample ? 'Sample' : ''"
              :disabled="scope.row.Sample || !['Arrangement', 'my_request'].includes(currentTab)"
              @change="($e) => onBatchRecordChange($e, scope.$index)"
            >
              <el-option
                v-for="option in computedOption as any[]"
                :disabled="!option.isSearch && scope.row.addFlag"
                :key="option.id"
                :value="option.id"
                :label="option.Name + (option.Reference ? ` - ${option.Reference}` : '')"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          label="备注"
          width="110"
          fixed
        >
          <template #default="scope">
            <el-input
              :disabled="!['Arrangement', 'my_request'].includes(currentTab)"
              v-model="scope.row.User_Notes"
              size="small"
              :rows="2"
              type="textarea"
              @change="scope.row.editFlag = true"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          label="箱数"
          width="80"
          :sortable="currentTab === 'Arrangement'"
          :sort-method="customSort1"
        >
          <template #default="scope">
            <el-input
              :disabled="!['Arrangement', 'my_request'].includes(currentTab)"
              v-model="scope.row.Carton"
              size="small"
              @change="scope.row.editFlag = true"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          label="唛头"
          width="220"
        >
          <template #default="scope">
            <el-input
              :disabled="!['Arrangement', 'my_request'].includes(currentTab)"
              v-model="scope.row.Marks_Nos"
              size="small"
              @change="scope.row.editFlag = true"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          label="货物名称"
          width="180"
        >
          <template #default="scope">
            <el-input
              :disabled="!['Arrangement', 'my_request'].includes(currentTab)"
              v-model="scope.row.Description_of_Goods"
              size="small"
              @change="scope.row.editFlag = true"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          label="货物材质"
          width="220"
        >
          <template #default="scope">
            <el-select
              :disabled="!['Arrangement', 'my_request'].includes(currentTab)"
              v-model="scope.row.Material_of_Goods"
              size="small"
              multiple
              @change="scope.row.editFlag = true"
            >
              <el-option
                v-for="i in goodMaterialOption"
                :key="i"
                :value="i"
                :label="i"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          label="数量"
          width="100"
          :sortable="currentTab === 'Arrangement'"
          :sort-method="customSort2"
        >
          <template #default="scope">
            <el-input
              :disabled="!['Arrangement', 'my_request'].includes(currentTab)"
              v-model="scope.row.Quantity"
              size="small"
              @change="changeTotal(scope.row)"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          label="单价(澳币/AUD)"
          :sortable="currentTab === 'Arrangement'"
          :sort-method="customSort3"
          width="145"
        >
          <template #default="scope">
            <el-input
              :disabled="!['Arrangement', 'my_request'].includes(currentTab)"
              v-model="scope.row.Unit_Price"
              size="small"
              @change="changeTotal(scope.row)"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          :sortable="currentTab === 'Arrangement'"
          :sort-method="requesterSort"
          label="负责人"
          fixed="right"
          width="120"
        >
          <template #default="scope">
            <el-input
              v-model="scope.row.Requester.name"
              size="small"
              disabled
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          :sortable="currentTab === 'Arrangement'"
          :sort-method="salesPersonSort"
          label="申请人"
          fixed="right"
          width="120"
        >
          <template #default="scope">
            <el-input
              v-model="scope.row.Sales_Person"
              size="small"
              disabled
            ></el-input>
          </template>
        </el-table-column>

        <el-table-column
          v-show="superUserIDList.includes(currentUser)"
          fixed="right"
          label="操作"
          width="100"
        >
          <template #default="scope">
            <el-tooltip
              content="新增未commit的行会被直接移除; 已commit的行只会标记, 正式commit后才会删除"
            >
              <el-button
                v-if="['Arrangement', 'my_request'].includes(currentTab)"
                type="danger"
                size="small"
                link
                @click="() => onDeleteRow(scope.row, scope.$index)"
              >
                删除
              </el-button>
            </el-tooltip>
            <el-button
              size="small"
              link
              type="primary"
              @click="print(scope.row)"
            >
              打印
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          label="自动发送"
          width="75"
          fixed="right"
        >
          <template #default="scope">
            <el-tooltip
              content="配合'删除'操作可转移到候选货物列表中, 下次新建航次CRM会自动将其加入"
            >
              <el-checkbox
                :disabled="!['Arrangement'].includes(currentTab)"
                @change="
                  () => {
                    if (scope.row.Force_Send) {
                      scope.row.editFlag = true
                    }
                  }
                "
                v-model="scope.row.Force_Send"
              ></el-checkbox>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="重量 (KG)"
          :sortable="currentTab === 'Arrangement'"
          :sort-method="customSort4"
          width="100"
        >
          <template #default="scope">
            <el-input
              :disabled="!['Arrangement', 'my_request'].includes(currentTab)"
              v-model="scope.row.Weight"
              size="small"
              @change="scope.row.editFlag = true"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          :sortable="currentTab === 'Arrangement'"
          :sort-method="customSort5"
          fixed="right"
          label="体积 m&sup3;"
          width="95"
        >
          <template #default="scope">
            <el-button
              @click="openCubeDialog(scope)"
              :disabled="!['Arrangement', 'my_request'].includes(currentTab)"
              type="primary"
              size="small"
              text
            >
              {{ scope.row.Cube || '点击输入' }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          :sortable="currentTab === 'Arrangement'"
          :sort-method="customSort6"
          fixed="right"
          label="总离岸价 (澳币/AUD)"
          width="165"
        >
          <template #default="scope">
            <el-input
              v-model="scope.row.Total_FOB"
              size="small"
              disabled
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          :sortable="currentTab === 'Arrangement'"
          :sort-method="refSort"
          label="Reference"
          fixed="right"
          width="110"
        >
          <template #default="scope">
            <div class="">{{ scope.row.Reference || scope.row.PO_Number }}</div>
          </template>
        </el-table-column>
        <el-table-column
          :selectable="calcSelectAble"
          type="selection"
          width="40"
          fixed="right"
        />
      </el-table>

      <el-drawer
        v-model:model-value="printDrawerVisible"
        :size="'1050px'"
        :title="'打印唛 (注意先写完唛内容和宽高最后再调页数, 不然可能会很卡)'"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <comp-print
          v-if="printDrawerVisible"
          :autoOpenQRCode="false"
          :content="[currentPrintRow.Marks_Nos || '']"
          :scene="'QC'"
        />
      </el-drawer>
      <el-drawer
        v-model:model-value="mapDrawerVisible"
        :size="'1050px'"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :destroy-on-close="true"
        :with-header="false"
        header-class="mb-1"
      >
        <div class="relative h-[20px]">
          <span
            @click="closeMapDrawer"
            class="absolute top-[-16px] right-0 text-gray-600 text-sm cursor-pointer"
          >
            关闭地图窗口
          </span>
        </div>
        <div
          id="mapDrawer"
          class="h-[100%]"
        ></div>
      </el-drawer>
    </div>
    <el-dialog
      style="margin-top: 35vh"
      title="体积输入(直接输入体积, 或输入长宽高自动计算)"
      :modelValue="cubeDialogVisible >= 0"
      @close="closeCubeDialog"
      width="400px"
    >
      <el-form
        label-position="right"
        label-width="95px"
      >
        <el-form-item label="长短单位">
          <el-radio-group v-model="unitType">
            <el-radio-button :label="1">米 (m)</el-radio-button>
            <el-radio-button :label="2">厘米 (cm)</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="`length (${unitType === 1 ? 'm' : 'cm'})`">
          <el-input v-model="cubeForm.l"></el-input>
        </el-form-item>
        <el-form-item :label="`width (${unitType === 1 ? 'm' : 'cm'})`">
          <el-input v-model="cubeForm.w"></el-input>
        </el-form-item>
        <el-form-item :label="`height (${unitType === 1 ? 'm' : 'cm'})`">
          <el-input v-model="cubeForm.h"></el-input>
        </el-form-item>
        <el-form-item label="箱数(整数)">
          <el-input v-model="cubeForm.Carton"></el-input>
        </el-form-item>
        <el-form-item label="cube (m³)">
          <el-input v-model="cubeForm2.c"></el-input>
        </el-form-item>
        <el-form-item>
          <div class="w-full flex justify-center">
            <el-button
              size="small"
              type="primary"
              @click="commitCube"
            >
              确定
            </el-button>
            <el-button
              size="small"
              @click="closeCubeDialog"
            >
              取消
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
    <comp-temp-ship
      v-model:visible="tempShipVisible"
      :id="tempShipID"
      :current-tab="currentTab"
      :good-material-option="goodMaterialOption"
    ></comp-temp-ship>
  </div>
</template>

<script lang="ts" setup>
import { defineComponent, ref, watch, computed, nextTick } from 'vue'
import {
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
  ElTabs,
  ElTabPane,
  ElTable,
  ElTableColumn,
  ElDatePicker,
  ElTooltip,
  ElSelect,
  ElOption,
  ElMessage,
  ElMessageBox,
  ElNotification,
  ElDrawer,
  ElDialog,
  ElCheckbox,
  ElRadio,
  ElRadioGroup,
  ElRadioButton,
} from 'element-plus'
import cloneDeep from 'lodash.clonedeep'
import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc.js'
import timezone from 'dayjs/plugin/timezone.js'
import debounce from 'lodash.debounce'
import compPrint from '@/components/print.vue'
import request from '@/utils/axios'
import {
  customSort1,
  customSort2,
  customSort3,
  customSort4,
  customSort5,
  customSort6,
  refSort,
  requesterSort,
  salesPersonSort,
  batchRecordSort,
  customMapData,
  calcSelectAble,
  calcRowStyle,
  exportSubTable,
} from './func'
import compTempShip from './compTempShip.vue'

defineComponent({
  name: 'ComponentCargoConsolidationRequest',
})

const currentUser = ref('')
const currentUserName = ref('')
const currentUserRawData = ref({} as any)
let loading = ref(false)
let list = ref([] as any[])
let currentTab = ref('all')

let tabs = [
  {
    label: 'All',
    value: 'all',
  },
  {
    label: 'Avaliable',
    value: 'avaliable',
  },
  {
    label: 'Closed Voyage',
    value: 'voyage_closed',
  },
  {
    label: 'My Request',
    value: 'my_request',
  },
]

dayjs.extend(utc)
dayjs.extend(timezone)

let finalTabs = ref([] as any[])
finalTabs.value = cloneDeep(tabs)

let computedList = computed(() => {
  return list.value.filter((i: any) => {
    let condition = true
    switch (currentTab.value) {
      case 'avaliable':
        condition = i.Status && i.Status === '可用'
        break
      case 'voyage_closed':
        condition = ['已截仓', '已确认', '已发出', '已到达'].includes(i.Status)
        break
    }
    return condition
  })
})

let dateRange = ref([] as any[])
const generateDateRange = (days = 7) => {
  const today = new Date()
  const endDate = new Date()
  endDate.setDate(today.getDate() + days)
  return [today, endDate]
}

const dateShortcuts = ref([
  {
    text: 'Next 3 days',
    value: generateDateRange(3),
  },
  {
    text: 'Next week',
    value: generateDateRange(7),
  },
  {
    text: 'Next 14days',
    value: generateDateRange(14),
  },
] as any[])
function getDefaultRange() {
  const today = dayjs()
  const lastMonthFirstDay = today.subtract(1, 'month').startOf('month').format('YYYY-MM-DD')
  const nextMonthLastDay = today.add(1, 'month').endOf('month').format('YYYY-MM-DD')

  return [lastMonthFirstDay, nextMonthLastDay]
}
dateRange.value = getDefaultRange()

let formatCutOffDateTime = (str: string) =>
  str?.length ? dayjs.utc(str).tz('Asia/Shanghai').format('YYYY-MM-DD HH:mm:ss') : ''

const clearSubList = () => {
  subList.value = []
  subListBackup = []
  currentRow.value = {}
}

let getList = () => {
  loading.value = true
  zoho.CRM.API.coql({
    select_query:
      'select Container_Number,Name,Forwarder,ETD,ATD,ETA,ATA,Cut_Off_Date,Owner,Status,Modified_Time,SubscriptionId,Carrier,Booking_Number,GRN,Cut_Off_Date_Time from Sea_Freight_Table' +
      " where ETD between '" +
      `${dateRange.value.map((i) => dayjs(i).format('YYYY-MM-DD')).join("' and '")}` +
      "'",
  })
    .then((res: any) => {
      if (Array.isArray(res.data) && res.data.length) {
        list.value = res.data.sort(
          (a: any, b: any) =>
            new Date(b.Cut_Off_Date).getTime() - new Date(a.Cut_Off_Date).getTime(),
        )
      } else if (res.status === 204) {
        ElNotification({
          type: 'warning',
          title: 'No Data Found',
          message: res.statusText || `zoho api return: ${res.status}`,
          duration: 3000,
        })
        list.value = []
      }
      clearSubList()
    })
    .finally(() => (loading.value = false))
}

let currentRow = ref({} as any)
let subList = ref([] as any[])
// 未经过滤的crm数据
let subListBackup: any[] = []

watch(currentTab, (value: string) => {
  // 切到可用tab, 但是当前行是不是 可用 状态
  let notAvaliable = value === 'avaliable' && currentRow.value.Status !== '可用'

  // 切到关闭tab, 但当前行不是‘关闭’状态
  let notClose =
    value === 'voyage_closed' && !['已截仓', '已确认', '已发出'].includes(currentRow.value.Status)

  if (notAvaliable || notClose) {
    clearSubList()
  } else {
    generateSubList()
  }
})

const generateSubList = () => {
  // clonedeep 是因为数据里面有 object array, 担心浅复制到表单变量会影响到原始数据
  subList.value = cloneDeep(
    subListBackup
      .filter(
        (i: any) =>
          i.Parent_Id.id === currentRow.value.id &&
          (currentTab.value === 'my_request' ? i.Sales_Person === currentUserName.value : true),
      )
      .map((i: any) => ({
        ...i,
        Requester: i.Requester?.id
          ? {
              name: i.Requester.name || '',
              id: i.Requester.id,
            }
          : { name: '', id: '' },
        Sample: i.Sample || false,
        batchRecord: i.Batch_Record?.id || '',
        addFlag: false,
        editFlag: false,
        deleteFlag: false,
      })),
  )
}
const changeTotal = (row: any) => {
  row.editFlag = true
  row.Total_FOB = (Number(row.Unit_Price) * Number(row.Quantity)).toFixed(2)
}

/**
 *  用来增加新行的数据模版
 */
const newLineTemplate = {
  addFlag: true,
  editFlag: true,
  deleteFlag: false,
  batchRecord: '',
  // 提交表单前删掉以上字段
  // id: '',
  Sample: false,
  Batch_Record: {
    name: '',
    id: '',
  } as any,
  Sales_Order: '',
  Purchase_Order: '',
  Reference: '',
  PO_Number: '',
  Parent_Id: {
    name: '',
    id: '',
  } as any,
  Carton: '',
  Marks_Nos: '',
  Description_of_Goods: '',
  Material_of_Goods: [],
  Quantity: '',
  Unit_Price: '',
  Weight: '',
  Cube: '',
  Total_FOB: '',
  Requester: { name: '', id: '' } as any,
  Sales_Person: '', // 申请人
  User_Notes: '',
}
// 用在弹窗里面给批次记录做候选项
let batchListOption = computed(() =>
  subList.value
    .filter((i) => i.Batch_Record && i.Batch_Record.name && i.Batch_Record.name.length > 0)
    .map((i) => ({
      Name: i.Batch_Record.name || '',
      id: i.Batch_Record.id || '',
      isSearch: false, // 用来区分是搜索出来的还是原始数据
    }))
    // ai生成的去重逻辑.
    .filter(
      (item, index, self) =>
        index === self.findIndex((t) => t.Name === item.Name && t.id === item.id),
    ),
)
let computedOption = computed(() => {
  return qcList.value.concat(batchListOption.value)
})
let getSubList = (e: any = {}) => {
  if (e.id) currentRow.value = e
  loading.value = true
  zoho.CRM.API.searchRecord({
    Entity: 'Sea_Freight_Details',
    Type: 'criteria',
    Query: `(Parent_Id:equals:${currentRow.value.id})`,
    delay: false,
  })
    .then((res: any) => {
      if (Array.isArray(res.data) && res.data.length) {
        subListBackup = cloneDeep(res.data)
      } else {
        subListBackup = []
      }

      generateSubList()
      newLineTemplate.Parent_Id = { id: currentRow.value.id }
      newLineTemplate.Sales_Person = currentUserName.value
      newLineTemplate.Requester = {
        id: currentUser.value,
        name: currentUserName.value,
      }
    })
    .finally(() => (loading.value = false))
}
// 货物材质候选数据
const goodMaterialOption = ref([] as any[])
// 动态获取货物材质候选数据
let getGoodMaterialOption = () => {
  request.post('/common/getWebsiteSubform', { id: '4791186000359651051' }).then((resp: any) => {
    const res = resp.data.result || {}
    if (!Array.isArray(res.data) || res.data.length < 1) return
    goodMaterialOption.value =
      res.data[0].Website_Subform.map((i: any) => i.Website_Subform_Value) || []
  })
}
getGoodMaterialOption()

const addBulkProduct = () => {
  let temp = cloneDeep(newLineTemplate)
  temp.Sample = false
  subList.value.unshift(temp)
}
const addSample = () => {
  let temp = cloneDeep(newLineTemplate)
  temp.Sample = true
  subList.value.unshift(temp)
}

const onDeleteRow = (row: any, index: number = -1) => {
  if (row.addFlag) {
    subList.value.splice(index, 1)
  } else {
    row.deleteFlag = true
    ElNotification({
      type: 'warning',
      title: '已标记删除',
      duration: 3000,
      message: '点 提交 按钮后会正式删除. 误操作请点击 放弃改动.',
    })
  }
}

const onBatchRecordChange = ($e: string, line = -1) => {
  const temp = computedOption.value.filter((i) => i.id === $e)
  let result: any = {}
  if (temp.length) {
    result = cloneDeep(temp[0])
  }

  if (line > -1) {
    // 主页面数据编辑
    subList.value[line].editFlag = true
    subList.value[line].Batch_Record = { id: result.id, name: result.Name }
    if (result.Owner) {
      subList.value[line].Requester = {
        name: result.Owner.name,
        id: result.Owner.id,
      }
    }
    subList.value[line].Sales_Order = result.Sales_Order || ''
    subList.value[line].Purchase_Order = result.Purchase_Order || ''
    subList.value[line].Reference = result.Reference || ''
    subList.value[line].PO_Number = result.PO_Number || ''
    // 如果对应行的唛头为空, 则用批次记录的名称填充
    if (!subList.value[line].Marks_Nos || subList.value[line].Marks_Nos.length < 1) {
      subList.value[line].Marks_Nos = result.Job_Name || ''
    }
    if (!subList.value[line].Quantity) {
      subList.value[line].Quantity = result.Quantity || ''
    }
    if (!subList.value[line].Unit_Price) {
      subList.value[line].Unit_Price = result.List_Price || ''
    }
  }
}
const tempShipID = '4791186000388831863'
const commit = async () => {
  let temp = cloneDeep(subList.value)
  let formData = customMapData(temp.filter((i) => !i.deleteFlag))

  const emptyUserNotesList: number[] = []
  const emptyCartonList: number[] = [] // 箱数
  const emptyMarksNosList: number[] = [] // 唛头
  const emptyNameList: number[] = [] // 货物名称 Description_of_Goods
  const emptyCubeList: number[] = [] // 体积

  formData.forEach((i, index) => {
    if (!i.User_Notes) {
      emptyUserNotesList.push(index)
    }
    if (!i.Carton) {
      emptyCartonList.push(index)
    }
    if (!i.Marks_Nos) {
      emptyMarksNosList.push(index)
    }
    if (!i.Description_of_Goods) {
      emptyNameList.push(index)
    }
    if (!i.Cube) {
      emptyCubeList.push(index)
    }
  })

  if (emptyUserNotesList.length) {
    ElNotification({
      title: '请检查表单, 备注是必填的',
      message: `第 ${emptyUserNotesList.map((i) => i + 1).join(', ')} 行的备注数据, 不能为空`,
      duration: 5000,
    })
    return
  }
  if (emptyCartonList.length) {
    ElNotification({
      title: '请检查表单, 箱数是必填的',
      message: `第 ${emptyCartonList.map((i) => i + 1).join(', ')} 行的箱数数据, 不能为空`,
      duration: 5000,
    })
    return
  }
  if (emptyMarksNosList.length) {
    ElNotification({
      title: '请检查表单, 唛头是必填的',
      message: `第 ${emptyMarksNosList.map((i) => i + 1).join(', ')} 行的唛头数据, 不能为空`,
      duration: 5000,
    })
    return
  }
  if (emptyNameList.length) {
    ElNotification({
      title: '请检查表单, 货物名称是必填的',
      message: `第 ${emptyNameList.map((i) => i + 1).join(', ')} 行的货物名称数据, 不能为空`,
      duration: 5000,
    })
    return
  }
  if (emptyCubeList.length) {
    ElNotification({
      title: '请检查表单, 体积是必填的',
      message: `第 ${emptyCubeList.map((i) => i + 1).join(', ')} 行的体积数据, 不能为空`,
      duration: 5000,
    })
    return
  }

  formData = formData.concat(
    temp
      .filter((i) => i.deleteFlag)
      .map((i) => ({ id: i.id, _delete: null, Material_of_Goods: null })),
  )
  let params = {
    id: currentRow.value.id,
    Sea_Freight_array: formData,
    Sales_Person: currentUserName.value,
    Sales_Person_Obj: {
      id: currentUser.value,
      name: currentUserName.value,
    },
  }

  console.log(params, '保存 无转移的数据')
  let formData2 = customMapData(temp.filter((i) => i.deleteFlag && i.Force_Send)).map((i) => {
    // 转移之前覆盖 Parent_Id, 否则按照customMapData的逻辑会被存成原航次的id
    let t = {
      ...i,
      Parent_Id: { id: tempShipID },
    }
    try {
      delete t.id // 相当于在新建记录.不删除原id的话, 不一点能转移成功(crm限制), 并且后面原航次的保存会把这个id对应的记录删除
    } catch {
      console.log(t, '组装转移数据时删除id出错')
    }
    return t
  })

  let params2 = {
    id: tempShipID,
    Sea_Freight_array: formData2,
    Sales_Person: currentUserName.value,
    Sales_Person_Obj: {
      id: currentUser.value,
      name: currentUserName.value,
    },
  }
  console.log(params2, '保存 要转移的数据')
  loading.value = true
  let sendToTempShipFlag = true // (转移到临时航次) 的状态
  if (formData2.length) {
    let response2 = await request.post('/sea_freight/updateSeaFreightDataV2', params2)
    if (response2.data.code !== 1) {
      sendToTempShipFlag = false
      ElMessage.error('转移到临时航次失败, 请稍后再试或者联系管理员')
      loading.value = false
      return
    }
    let result2 = response2.data.result || { data: [] }
    if (
      !(
        Array.isArray(result2.data) &&
        result2.data.length &&
        result2.data.every((i: any) => i.status === 'success')
      )
    ) {
      sendToTempShipFlag = false
      ElNotification({
        title: '部份内容转移失败',
        message: '建议刷新再试或者联系管理员',
        duration: 10000,
      })
    }
  }
  if (sendToTempShipFlag === false) {
    loading.value = false
    return
  }
  request
    .post('/sea_freight/updateSeaFreightDataV2', params)
    .then((res) => {
      if (res.data.code !== 1) {
        ElMessage.error('保存出错')
        loading.value = false
        return
      }
      let result = res.data.result || { data: [] }
      if (
        Array.isArray(result.data) &&
        result.data.length &&
        result.data.every((i: any) => i.status === 'success')
      ) {
        ElNotification({
          title: '保存成功',
          message: '正在刷新数据',
          duration: 3000,
        })
      } else {
        ElNotification({
          title: '部份内容保存失败',
          message: '建议刷新再试或者联系管理员',
          duration: 10000,
        })
      }
      getSubList(currentRow.value)
    })
    .catch((e) => {
      console.log(e, 'commit error')
      loading.value = false
    })
}
const commitWithSDK = async () => {
  let temp = cloneDeep(subList.value)
  let formData = customMapData(temp.filter((i) => !i.deleteFlag))

  const emptyUserNotesList: number[] = []
  const emptyCartonList: number[] = [] // 箱数
  const emptyMarksNosList: number[] = [] // 唛头
  const emptyNameList: number[] = [] // 货物名称 Description_of_Goods
  const emptyCubeList: number[] = [] // 体积

  formData.forEach((i, index) => {
    if (!i.User_Notes) {
      emptyUserNotesList.push(index)
    }
    if (!i.Carton) {
      emptyCartonList.push(index)
    }
    if (!i.Marks_Nos) {
      emptyMarksNosList.push(index)
    }
    if (!i.Description_of_Goods) {
      emptyNameList.push(index)
    }
    if (!i.Cube) {
      emptyCubeList.push(index)
    }
  })

  if (emptyUserNotesList.length) {
    ElNotification({
      title: '请检查表单, 备注是必填的',
      message: `第 ${emptyUserNotesList.map((i) => i + 1).join(', ')} 行的备注数据, 不能为空`,
      duration: 5000,
    })
    return
  }
  if (emptyCartonList.length) {
    ElNotification({
      title: '请检查表单, 箱数是必填的',
      message: `第 ${emptyCartonList.map((i) => i + 1).join(', ')} 行的箱数数据, 不能为空`,
      duration: 5000,
    })
    return
  }
  if (emptyMarksNosList.length) {
    ElNotification({
      title: '请检查表单, 唛头是必填的',
      message: `第 ${emptyMarksNosList.map((i) => i + 1).join(', ')} 行的唛头数据, 不能为空`,
      duration: 5000,
    })
    return
  }
  if (emptyNameList.length) {
    ElNotification({
      title: '请检查表单, 货物名称是必填的',
      message: `第 ${emptyNameList.map((i) => i + 1).join(', ')} 行的货物名称数据, 不能为空`,
      duration: 5000,
    })
    return
  }
  if (emptyCubeList.length) {
    ElNotification({
      title: '请检查表单, 体积是必填的',
      message: `第 ${emptyCubeList.map((i) => i + 1).join(', ')} 行的体积数据, 不能为空`,
      duration: 5000,
    })
    return
  }

  let params = {
    APIData: {
      id: currentRow.value.id,
      Sea_Freight_Details: formData,
    },
    Entity: 'Sea_Freight_Table',
    trigger: ['workflow', 'approval'],
  }

  console.log(params, '保存 无转移的数据')
  let formData2 = customMapData(temp.filter((i) => i.deleteFlag && i.Force_Send)).map((i) => {
    // 转移之前覆盖 Parent_Id, 否则按照customMapData的逻辑会被存成原航次的id
    let t = {
      ...i,
      Parent_Id: { id: tempShipID },
    }
    try {
      delete t.id // 相当于在新建记录.不删除原id的话, 不一点能转移成功(crm限制), 并且后面原航次的保存会把这个id对应的记录删除
      delete t.parent_id
    } catch {
      console.log(t, '组装转移数据时删除id出错')
    }
    return t
  })

  let params2 = {
    APIData: {
      Temporary_Transform_Record: true,
      Sea_Freight_Details: formData2,
      Name: '临时调动记录（非真正航次）',
      ETD: '1900-01-01',
      ETA: '1900-01-01',
    },
    Entity: 'Sea_Freight_Table',
    trigger: ['workflow', 'approval'],
  }
  console.log(params2, '保存 要转移的数据')
  loading.value = true
  let sendToTempShipFlag = true // (转移到临时航次) 的状态
  if (formData2.length) {
    let res2 = await zoho.CRM.API.insertRecord(params2)

    if (
      !(
        Array.isArray(res2.data) &&
        res2.data.length &&
        res2.data.every((i: any) => i.status === 'success')
      )
    ) {
      sendToTempShipFlag = false
      ElNotification({
        title: '部份内容转移失败',
        message: '建议刷新再试或者联系管理员',
        duration: 10000,
      })
    } else {
      return
    }
  }
  if (sendToTempShipFlag === false) {
    loading.value = false
    return
  }

  zoho.CRM.API.updateRecord(params)
    .then((res: any) => {
      if (
        Array.isArray(res.data) &&
        res.data.length &&
        res.data.every((i: any) => i.status === 'success')
      ) {
        ElNotification({
          title: '保存成功',
          message: '正在刷新数据',
          duration: 3000,
        })
      } else {
        ElNotification({
          title: '部份内容保存失败',
          message: '建议刷新再试或者联系管理员',
          duration: 10000,
        })
      }
      getSubList(currentRow.value)
    })
    .catch((e: any) => {
      console.log(e, 'commit error')
      loading.value = false
    })
}

let printDrawerVisible = ref(false)
let currentPrintRow = ref({} as any)
const print = (row: any) => {
  currentPrintRow.value = row
  printDrawerVisible.value = true
}

let qcList = ref([] as any[])
let loading2 = ref(false)

const search = (keyword: string) => {
  if (keyword.length < 2) return
  keyword = keyword.trim().toUpperCase()
  loading2.value = true
  zoho.CRM.API.searchRecord({
    Entity: 'QC_Record',
    Type: 'criteria',
    Query: `(Reference:in:${keyword})or(Reference:starts_with:${keyword})or(Purchase_Order.name:in:${keyword})or(Purchase_Order.name:starts_with:${keyword})`,
    delay: false,
  })
    .then((res: any) => {
      if (Array.isArray(res.data) && res.data.length) {
        qcList.value = res.data.map((i: any) => {
          return {
            ...i,
            isSearch: true,
          }
        })
      } else {
        qcList.value = []
        ElMessage.warning('No Data Found')
      }
    })
    .finally(() => (loading2.value = false))
}

const updateStatus = (status = '已确认') => {
  ElMessageBox.confirm(`确定要把该记录状态更新为"${status}"吗?`, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    loading.value = true
    zoho.CRM.API.updateRecord({
      Entity: 'Sea_Freight_Table',
      Trigger: ['workflow'],
      APIData: {
        id: currentRow.value.id,
        Status: status,
      },
    }).then((res: any) => {
      if (Array.isArray(res.data) && res.data.length && res.data[0].code === 'SUCCESS') {
        ElMessage.success('操作成功, 正在刷新数据')
        loading.value = false
        getList()
        clearSubList()
      } else {
        loading.value = false
        ElMessage.error('操作失败, 请稍后再试或者联系管理员')
      }
    })
  })
}
let bookingNumber = ref('')
const updateBookingNumber = () => {
  bookingNumber.value = bookingNumber.value.trim()
  if (!bookingNumber.value || !currentRow.value.id) {
    ElMessage.error('请填写订舱号')
    return
  }
  ElMessageBox.confirm(`确定要把该记录的订舱号更新为"${bookingNumber.value}"吗?`, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    loading.value = true
    zoho.CRM.API.updateRecord({
      Entity: 'Sea_Freight_Table',
      Trigger: ['workflow'],
      APIData: {
        id: currentRow.value.id,
        Booking_Number: bookingNumber.value,
      },
    }).then((res: any) => {
      if (Array.isArray(res.data) && res.data.length && res.data[0].code === 'SUCCESS') {
        ElMessage.success('操作成功, 正在刷新数据')
        loading.value = false
        bookingNumber.value = ''
        getList()
        clearSubList()
      } else {
        loading.value = false
        ElMessage.error('操作失败, 请稍后再试或者联系管理员')
      }
    })
  })
}

let containerNumber = ref('')
const updateContainerNumber = () => {
  containerNumber.value = containerNumber.value.trim()
  if (!containerNumber.value || !currentRow.value.id) {
    ElMessage.error('请填写柜号')
    return
  }
  ElMessageBox.confirm(`确定要把该记录的柜号更新为"${containerNumber.value}"吗?`, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    loading.value = true
    zoho.CRM.API.updateRecord({
      Entity: 'Sea_Freight_Table',
      Trigger: ['workflow'],
      APIData: {
        id: currentRow.value.id,
        Container_Number: containerNumber.value,
      },
    }).then((res: any) => {
      if (Array.isArray(res.data) && res.data.length && res.data[0].code === 'SUCCESS') {
        ElMessage.success('操作成功, 正在刷新数据')
        loading.value = false
        containerNumber.value = ''
        getList()
        clearSubList()
      } else {
        loading.value = false
        ElMessage.error('操作失败, 请稍后再试或者联系管理员')
      }
    })
  })
}
// @ts-ignore
const zoho = window.ZOHO
zoho.embeddedApp.on('PageLoad', function () {
  zoho.CRM.CONFIG.getCurrentUser().then(function (data: any) {
    if (Array.isArray(data.users) && data.users.length) {
      const user = data.users[0]
      // console.log(user, 'user')
      currentUser.value = user.id
      currentUserName.value = user.full_name || ''
      currentUserRawData.value = cloneDeep(user)
      getList()
    }
  })
})

zoho.embeddedApp.init()
const superUserIDList = ref([
  '4791186000259693001', // 小权限账号, 测试用. 目前是给jayson了.
  '4791186000022965001', // kava
  '4791186000052269001', // 物流部
])
watch(currentUserRawData, () => {
  if (!currentUserRawData.value.role) return false

  let result =
    /(CEO|Logistics)/g.test(currentUserRawData.value.role.name) ||
    superUserIDList.value.includes(currentUserRawData.value.role.id)

  if (result) {
    finalTabs.value = cloneDeep(tabs)
    finalTabs.value.push({
      label: 'Arrangement',
      value: 'Arrangement',
    })
  }
})

let computedWeight = computed(() => {
  return subList.value
    .reduce((t, c) => {
      t = t + Number(c.Weight)
      return t
    }, 0)
    .toFixed(2)
})
let computedCube = computed(() => {
  return subList.value
    .reduce((t, c) => {
      t = t + Number(c.Cube)
      return t
    }, 0)
    .toFixed(2)
})
let computedTotalFOB = computed(() => {
  return subList.value
    .reduce((t, c) => {
      t = t + Number(c.Total_FOB)
      return t
    }, 0)
    .toFixed(2)
})
let computedSelectedWeight = computed(() => {
  return selectedRow.value
    .reduce((t, c) => {
      t = t + Number(c.Weight)
      return t
    }, 0)
    .toFixed(2)
})
let computedSelectedCube = computed(() => {
  return selectedRow.value
    .reduce((t, c) => {
      t = t + Number(c.Cube)
      return t
    }, 0)
    .toFixed(2)
})
let computedSelectedTotalFOB = computed(() => {
  return selectedRow.value
    .reduce((t, c) => {
      t = t + Number(c.Total_FOB)
      return t
    }, 0)
    .toFixed(2)
})

// 订单轨迹地图插件
let mapDrawerVisible = ref(false)
const openMapDrawer = (row: any) => {
  mapDrawerVisible.value = true
  if ((window as any).Sgld) {
    nextTick(() => {
      ;(window as any).Sgld.createContainerTrack({
        id: 'mapDrawer',
        carrierCode: row.Carrier, // 船公司代码
        billNo: row.Booking_Number, // 提单号
        language: 'en', // 语言
      })
    })
  }
}
const closeMapDrawer = () => {
  mapDrawerVisible.value = false
}
let cubeDialogVisible = ref(-1)
let unitType = ref(1) // 1:m 2:cm
let cubeForm = ref({
  l: '',
  w: '',
  h: '',
  Carton: '' as string | number, // 箱数
})
let cubeForm2 = ref({
  c: '' as string | number, // 体积
})
watch(unitType, () => {
  cubeForm.value.l = Number(cubeForm.value.l) * (unitType.value === 1 ? 0.01 : 100) + ''
  cubeForm.value.w = Number(cubeForm.value.w) * (unitType.value === 1 ? 0.01 : 100) + ''
  cubeForm.value.h = Number(cubeForm.value.h) * (unitType.value === 1 ? 0.01 : 100) + ''
})
watch(
  cubeForm,
  () => {
    cubeForm2.value.c = (
      Number(cubeForm.value.l) *
      Number(cubeForm.value.w) *
      Number(cubeForm.value.h) *
      Number(cubeForm.value.Carton) *
      (unitType.value === 2 ? 0.000001 : 1)
    ).toFixed(2)
  },
  {
    immediate: true,
    deep: true,
  },
)
let openCubeDialog = (obj: any) => {
  let index = obj.$index
  if (index < 0 || index >= subList.value.length) return

  const row = subList.value[index]
  cubeForm.value.Carton = row.Carton || '1'
  cubeDialogVisible.value = index
  nextTick(() => {
    cubeForm2.value.c = row.Cube || ''
  })
}
let commitCube = () => {
  const row = subList.value[cubeDialogVisible.value]
  row.Cube = Number(cubeForm2.value.c).toFixed(2) || ''
  row.Carton = Number(cubeForm.value.Carton) || '1'
  row.editFlag = true
  closeCubeDialog()
}
let closeCubeDialog = () => {
  cubeDialogVisible.value = -1
  cubeForm.value.l = ''
  cubeForm.value.w = ''
  cubeForm.value.h = ''
  cubeForm.value.Carton = '1'
  cubeForm2.value.c = ''
}

let selectedRow = ref([] as any[])
const handleSelectionChange = (val: any[]) => {
  selectedRow.value = val
}
let tempShipVisible = ref(false)
const openTempShip = () => {
  tempShipVisible.value = true
}

// 别说代码行数太长搞屎山, 这个页面的功能上线之后改了6个版本, 每次都往上堆功能, 能不长嘛
</script>
<style lang="scss">
.page-cargo-consolidation {
  .el-table__body tr.current-row > td.el-table__cell {
    background-color: rgb(56, 163, 238);
    color: #fff;
  }
}
</style>
<style lang="scss" scoped>
.el-button.custom-button {
  height: 24px;
  line-height: 24px;
  background-image: linear-gradient(171deg, rgb(28, 74, 136) 49%, rgb(0, 130, 193) 100%);
  background-color: rgb(97, 165, 245);
  color: #fff;
  font-size: 13px;
  font-family: Zoho_Puvi_Bold sans-serif;
  border-radius: 6px;
  cursor: pointer;
  &:hover,
  &:active {
    background-image: linear-gradient(171deg, rgb(28, 74, 136) 49%, rgb(22, 208, 239) 100%);
    color: #fff;
  }
  &.fb {
    font-weight: 900;
  }
  &.small {
    height: 24px;
    line-height: 24px;
  }
}
</style>
