<template>
  <div class="">
    <en-table-layout :tableData="tableData.data" :loading="loading" @selection-change="handleSelectionChange">
      <template #toolbar>
        <div class="inner-toolbar w-11/12 flex justify-between">
          <div class="toolbar-btns">
            <el-button size="small" type="primary" @click="handleAddExpress">{{$t('add')}}</el-button>
          </div>
          <div class="toolbar-search">
            <!--  <en-table-search @search="searchEvent" placeholder="请输入关键字" /> -->
          </div>
        </div>
      </template>
      <template #table-columns>
        <el-table-column prop="name" :label="$t('companyName')" />
        <el-table-column prop="code" :label="$t('express_code')" />
        <el-table-column prop="kdcode" :label="$t('express_kdcode')" />
        <el-table-column :label="$t('user_state')" :formatter="disabledStatus" />
        <el-table-column :label="$t('operate')" min-width="200">
          <template #default="scope">
            <el-button size="small" type="primary" v-if="checkPermission(['logisticsCompany:edit'])" @click="handleEditExpress(scope.$index, scope.row)"
              >{{$t('edit')}}</el-button
            >
            <el-button
              v-if="scope.row.disabled === 'OPEN' && checkPermission(['logisticsCompany:editStatus'])"
              size="small"
              type="danger"
              @click="handleDisabledExpress(scope.$index, scope.row)"
              >{{$t('disable')}}</el-button
            >
            <el-button
              v-if="scope.row.disabled === 'CLOSE' && checkPermission(['logisticsCompany:editStatus'])"
              size="small"
              type="success"
              @click="handleDisabledExpress(scope.$index, scope.row)"
              >{{$t('open')}}</el-button
            >
            <el-button size="small" v-if="checkPermission(['logisticsCompany:delete'])" type="danger" @click="handleDeleteExpress(scope.$index, scope.row)"
              >{{$t('delete')}}</el-button
            >
          </template>
        </el-table-column>
      </template>
    </en-table-layout>

    <el-pagination
      v-if="tableData"
      v-model:current-page="params.page_no"
      v-model:page-size="params.page_size"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="tableData.data_total"
      @size-change="handlePageSizeChange"
      @current-change="handlePageCurrentChange"
    />

    <el-dialog v-model="dialogExpressVisible" :title="$t('express')" :close-on-click-modal="false" :close-on-press-escape="false" class="!rounded-lg">
      <el-form :model="expressForm" :rules="expressRules" ref="expressFormRef" label-width="120px">
        <el-form-item :label="$t('express_title')" prop="name">
          <el-input v-model="expressForm.name"></el-input>
        </el-form-item>
        <el-form-item :label="$t('express_code')" prop="code">
          <el-input v-model="expressForm.code"></el-input>
        </el-form-item>
        <el-form-item :label="$t('express_kdcode')" prop="kdcode" v-if="expressForm.is_waybill">
          <el-input v-model="expressForm.kdcode"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogExpressVisible = false">{{$t('cancel')}}</el-button>
          <el-button type="primary" @click="submitExpressForm">{{$t('submit')}}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
  
  <script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import * as API_Express from '@/api/express';
import { useI18n } from 'vue-i18n';
const { t } = useI18n();

// 定义响应式数据
const loading = ref(false);
const params = reactive({
  page_no: 1,
  page_size: 20,
});
const tableData = ref<any>({});
const expressForm = ref<any>({});
const dialogExpressVisible = ref(false);
const expressFormRef = ref();

// 计算属性：表单验证规则
const expressRules = computed(() => {
  return {
    name: [{ required: true, message: t('place')+t('express_title')+'!', trigger: 'blur' }],
    code: [{ required: true, message: t('place')+t('express_code')+'!', trigger: 'blur' }],
    kdcode: [{ required: expressForm.value.is_waybill, message:t('place')+t('express_kdcode')+'!', trigger: 'blur' }],
  };
});

// 生命周期钩子
onMounted(() => {
  getExpressList();
});

const handleSelectionChange = (val: any[]) => {
};
// 方法定义
const handlePageSizeChange = (size: number) => {
  params.page_size = size;
  getExpressList();
};

const handlePageCurrentChange = (page: number) => {
  params.page_no = page;
  getExpressList();
};

const disabledStatus = (row: any) => {
  return row.disabled === 'OPEN' ? '已开启' : '已禁用';
};

const handleAddExpress = () => {
  expressForm.value = { is_waybill: 0, formItems: [] };
  dialogExpressVisible.value = true;
  expressFormRef.value?.clearValidate();
};

const handleEditExpress = (index: number, row: any) => {
  const params = JSON.parse(JSON.stringify(row));
  if (typeof params.is_waybill !== 'number') {
    params.is_waybill = 0;
  }

  expressForm.value = {
    name: params.name,
    code: params.code,
    is_waybill: params.is_waybill,
    kdcode: params.kdcode,
    id: params.id,
  };

  dialogExpressVisible.value = true;
  expressFormRef.value?.clearValidate();
};

const submitExpressForm = () => {
  expressFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      const { id } = expressForm.value;
      let form = JSON.parse(JSON.stringify(expressForm.value));
      if (!id) {
        API_Express.addExpress(form).then(() => {
          dialogExpressVisible.value = false;
          ElMessage.success(t('add_success')+'!');
          getExpressList();
        });
      } else {
        form.formItems = [];
        API_Express.editExpress(id, form).then((response) => {
          dialogExpressVisible.value = false;
          ElMessage.success(t('sub_success')+'!');
          // 更新表格数据
          const index = tableData.value.data.findIndex((item: any) => item.id === id);
          if (index !== -1) {
            tableData.value.data[index] = response;
          }
        });
      }
    } else {
      ElMessage.error(t('form_erroe'));
    }
  });
};

const handleDeleteExpress = (index: number, row: any) => {
  ElMessageBox.confirm(t('express_company_info'), t('prompt'), { type: 'warning' })
    .then(() => {
      API_Express.deleteExpress(row.id).then(() => {
        ElMessage.success(t('del_success'));
        getExpressList();
      });
    })
    .catch(() => {});
};

const handleDisabledExpress = (index: number, row: any) => {
  ElMessageBox.confirm(t('operate_info'), t('prompt'), { type: 'warning' })
    .then(() => {
      API_Express.openDisableExpress(row.id, row.disabled === 'OPEN' ? 'CLOSE' : 'OPEN').then(() => {
        ElMessage.success(t('operate_success'));
        getExpressList();
      });
    })
    .catch(() => {});
};

const getExpressList = () => {
  loading.value = true;
  API_Express.getExpressList(params)
    .then((response) => {
      loading.value = false;
      tableData.value = response;
    })
    .catch(() => {
      loading.value = false;
    });
};

// 权限检查函数（需要根据实际情况实现）
const checkPermission = (permissions: string[]) => {
  // 实现权限检查逻辑
  return true;
};
</script>