<script setup lang="ts">
import { nextTick, ref } from 'vue'
import SplitDiv from '@/components/splitDiv/splitDiv.vue'
import {
  getLogisticsLog,
  IForm,
  ILogisticsCompany,
  ILogisticsCompanyData,
  ILogisticsList,
  logisticsCompany,
  logisticsCompanyAdd,
  logisticsCompanyAllCodelist,
  logisticsCompanyDelete,
  logisticsCompanyUpdate,
} from '@/api/logistics.ts'
import LogDialog from '@/views/logistics/components/LogDialog.tsx'

interface LogList {
  id?: number
  createTime?: string
  description?: string
}

const otherFields = ref<string[]>([])
const logDialogVisible = ref<boolean>(false)
const searchForm = ref({
  name: '',
  code: '',
})

const selections = ref<ILogisticsCompany[]>([])
const formRef = ref()
const logList = ref<LogList[]>([])
const logisticsList = ref<ILogisticsList[]>([])
const form = ref<IForm>({
  name: '',
  code: '',
  contact: '',
  phone: '',
  siteUrl: '',
  address: '',
  apiData: {},
})
const createData = ref({
  title: '',
  show: false,
  isEdit: false,
  form: {
    locationName: '',
    locationCode: '',
    pickingOrder: '',
    warehouseName: '',
    warehouseId: '',
    remark: '',
  },
})
const rules = {
  code: [{ required: true, message: '请选择物流公司编码', trigger: 'change' }],

  contact: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入电话/手机', trigger: 'blur' }],
  siteUrl: [{ required: true, message: '请输入网址', trigger: 'blur' }],
  address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
}
const leftData = ref<ILogisticsCompany[]>([])
const pagination = ref<ILogisticsCompanyData>({
  pageSize: 50,
  currentPage: 1,
  total: 0,
})

async function getData() {
  const res = await logisticsCompany({
    ...pagination.value,
    ...searchForm.value,
  })
  console.log(res)
  leftData.value = res.data.records
  pagination.value.total = res.data.total
}

const handleSelectionChange = (data: ILogisticsCompany[]) => {
  selections.value = data
}
const handleSizeChange = (pageSize: number) => {
  pagination.value.pageSize = pageSize
  getData()
}
const handleCurrentChange = (currentPage: number) => {
  pagination.value.currentPage = currentPage
  getData()
}
const handleConfirm = async () => {
  await formRef.value?.validate()
  if (!createData.value.isEdit) {
    await logisticsCompanyAdd(form.value)
  } else {
    await logisticsCompanyUpdate(form.value)
  }
  createData.value.show = false
  ElMessage.success('操作成功')
  await getData()
}
const handleShowLog = async (row: ILogisticsCompany) => {
  const { data } = await getLogisticsLog({
    logType: 'logistics_company',
    relaId: row.id as number,
  })
  logDialogVisible.value = true
  logList.value = data
}
const handleBatchDelete = async (row: ILogisticsCompany | null) => {
  if (!row && !selections.value.length) {
    return ElMessage.warning('请选择要删除的数据')
  }
  await ElMessageBox.confirm('确定要删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  const str =
    row && row.id
      ? row.id?.toString()
      : selections.value.map((el) => el.id).join(',')
  await logisticsCompanyDelete(str)
  ElMessage.success('删除成功')
  await getData()
}

const createWarehouse = () => {
  createData.value.show = true
  createData.value.isEdit = false
  createData.value.title = '新增物流公司'
  form.value = {
    name: '',
    code: '',
    contact: '',
    phone: '',
    siteUrl: '',
    address: '',
    apiData: {},
  }
  otherFields.value = []
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}
const updateWarehouse = (item: IForm) => {
  createData.value.show = true
  createData.value.isEdit = true
  otherFields.value = []
  createData.value.title = '修改物流公司'
  form.value = {
    id: item.id,
    name: item.name,
    code: item.code,
    contact: item.contact,
    phone: item.phone,
    siteUrl: item.siteUrl,
    address: item.address,
    apiData: item.apiData,
  }
  codeChange(item.code)
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

const codeChange = (v: string) => {
  const item = logisticsList.value.find((d) => d.code === v)
  if (item) {
    otherFields.value = Object.keys(item.apiData || {})
    form.value.name = item.basicsName
  }
}

const getLogisticsList = async () => {
  const { data } = await logisticsCompanyAllCodelist()
  logisticsList.value = data
}
getData()
getLogisticsList()
</script>

<template>
  <split-div>
    <template #top>
      <el-card>
        <el-form inline :model="searchForm">
          <el-form-item label="名称">
            <el-input
              v-model="searchForm.name"
              style="width: 140px"
              placeholder="请输入名称"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="编码">
            <el-input
              v-model="searchForm.code"
              style="width: 140px"
              placeholder="请输入编码"
              clearable
            ></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="getData">查询</el-button>
            <el-button type="success" @click="createWarehouse">新增</el-button>
            <el-button type="danger" @click="handleBatchDelete(null)"
              >删除</el-button
            >
          </el-form-item>
        </el-form>
      </el-card>
    </template>
    <template #bottom>
      <el-card style="height: 100%">
        <div class="manage">
          <div class="table-flex">
            <div class="left-table">
              <div class="table-container">
                <el-table
                  height="100%"
                  :data="leftData"
                  border
                  @selection-change="handleSelectionChange"
                >
                  <el-table-column type="selection" />
                  <el-table-column type="index" label="序号" width="60" />
                  <el-table-column
                    label="名称"
                    prop="name"
                    align="center"
                    show-overflow-tooltip
                  >
                  </el-table-column>
                  <el-table-column
                    label="编码"
                    prop="code"
                    align="center"
                    show-overflow-tooltip
                  >
                  </el-table-column>
                  <el-table-column
                    label="联系人"
                    prop="contact"
                    align="center"
                    show-overflow-tooltip
                  >
                  </el-table-column>

                  <el-table-column
                    label="电话"
                    prop="phone"
                    align="center"
                    show-overflow-tooltip
                  >
                  </el-table-column>

                  <el-table-column
                    label="网址"
                    prop="siteUrl"
                    align="center"
                    show-overflow-tooltip
                  >
                  </el-table-column>

                  <el-table-column
                    label="地址"
                    prop="address"
                    align="center"
                    show-overflow-tooltip
                  >
                  </el-table-column>
                  <el-table-column width="260" label="操作" align="center">
                    <template #default="{ row }">
                      <el-button
                        text
                        type="primary"
                        @click="updateWarehouse(row)"
                        >编辑</el-button
                      >
                      <el-button
                        text
                        type="danger"
                        @click="handleBatchDelete(row)"
                        >删除</el-button
                      >
                      <el-button text type="info" @click="handleShowLog(row)"
                        >操作日志</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <div class="pagination">
                <el-pagination
                  v-model:current-page="pagination.currentPage"
                  v-model:page-size="pagination.pageSize"
                  :page-sizes="[50, 100, 150, 200]"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="pagination.total"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                />
              </div>
            </div>
          </div>
          <LogDialog
            v-model="logDialogVisible"
            title="操作日志"
            @close="logDialogVisible = false"
          >
            <div
              v-for="item in logList"
              :key="item.id"
              style="margin-bottom: 8px"
            >
              <span style="margin-right: 10px">{{ item.createTime }}</span>
              <span>{{ item.description }}</span>
            </div>
          </LogDialog>
          <el-dialog
            v-model="createData.show"
            :close-on-click-modal="false"
            width="900px"
            :title="createData.title"
          >
            <el-form
              v-if="createData.show"
              ref="formRef"
              style="padding: 30px"
              label-width="110px"
              :rules="rules"
              :model="form"
              class="el-row"
            >
              <el-form-item class="el-col-12" label="物流公司编码" prop="code">
                <el-select
                  v-model="form.code"
                  clearable
                  filterable
                  @change="codeChange"
                >
                  <el-option
                    v-for="it in logisticsList"
                    :key="it.code"
                    :label="it.code"
                    :value="it.code"
                  >
                    {{ it.code }}
                    <span
                      style="font-size: 14px; color: #999; line-height: 24px"
                    >
                      ({{ it.basicsName }})
                    </span>
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item class="el-col-12" label="名称">
                <el-input
                  v-model="form.name"
                  clearable
                  disabled
                  placeholder="选择物流公司编码后展示"
                ></el-input>
              </el-form-item>
              <el-form-item class="el-col-12" label="联系人" prop="contact">
                <el-input
                  v-model="form.contact"
                  clearable
                  placeholder="请输入联系人"
                ></el-input>
              </el-form-item>
              <el-form-item class="el-col-12" label="电话/手机" prop="phone">
                <el-input
                  v-model="form.phone"
                  clearable
                  placeholder="请输入电话/手机"
                ></el-input>
              </el-form-item>
              <el-form-item class="el-col-12" label="网址" prop="siteUrl">
                <el-input
                  v-model="form.siteUrl"
                  clearable
                  placeholder="请输入网址"
                ></el-input>
              </el-form-item>
              <el-form-item class="el-col-12" label="地址" prop="address">
                <el-input
                  v-model="form.address"
                  clearable
                  placeholder="请输入地址"
                ></el-input>
              </el-form-item>
              <el-form-item
                v-for="o in otherFields"
                :key="o"
                class="el-col-12"
                required
                :label="o"
                :prop="`apiData.${o}`"
              >
                <el-input
                  v-model="form.apiData[o]"
                  clearable
                  :placeholder="`请输入${o}`"
                ></el-input>
              </el-form-item>
            </el-form>
            <template #footer>
              <el-button @click="createData.show = false">取消</el-button>
              <el-button type="primary" @click="handleConfirm">确定</el-button>
            </template>
          </el-dialog>
        </div>
      </el-card>
    </template>
  </split-div>
</template>

<style scoped lang="scss">
.el-card {
  ::v-deep(.el-card__body) {
    height: 100%;
  }
}

.manage {
  height: 100%;
  display: flex;
  flex-direction: column;

  .header {
    margin-bottom: 10px;
  }

  .table-flex {
    flex: 1;
    flex-shrink: 0;
    overflow: hidden;
    display: flex;
  }

  .right-table {
    flex: 1;
    margin-left: 10px;
    flex-shrink: 0;
  }

  .left-table {
    height: 100%;
    display: flex;
    width: 100%;
    flex-direction: column;

    .pagination {
      display: flex;
      margin-top: 10px;
      justify-content: center;
    }

    .table-container {
      flex: 1;
      flex-shrink: 0;
      overflow: hidden;
    }
  }
}
</style>
