<template>
  <div class="full-container-p24">
    <div class="mb30 df aic jcsb">
      <div class="df aic">
        <el-input
          v-model="searchKey"
          placeholder="请输入船厂名称"
          class="w300"
          @keyup.enter="handleSearch"
          clearable
          @clear="handleSearch"
        />
        <el-button class="ml10" type="primary" @click="handleSearch">
          搜索
        </el-button>
      </div>
      <el-button class="ml10" type="primary" @click="handleAdd">
        新增船厂
      </el-button>
    </div>

    <el-table border :data="tableData" stripe>
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column
        prop="shipyardName"
        label="船厂名称"
        min-width="150"
        align="center"
      />
      <el-table-column
        prop="shipyardAddress"
        label="地址"
        min-width="200"
        align="center"
      />
      <el-table-column
        prop="contactName"
        label="联系人"
        min-width="120"
        align="center"
      />
      <el-table-column
        prop="contactPhone"
        label="联系电话"
        min-width="150"
        align="center"
      />
      <el-table-column
        prop="shipyardIntroduce"
        label="船厂介绍"
        min-width="150"
        align="center"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        prop="shipyardDockNum"
        label="船坞数量"
        min-width="100"
        align="center"
      />
      <el-table-column
        prop="shipyardAnnualProdCapacity"
        label="年产能(艘)"
        min-width="100"
        align="center"
      />

      <el-table-column label="操作" width="180" align="center">
        <template #default="scope">
          <el-button type="primary" text @click="handleEdit(scope.row)">
            修改
          </el-button>
          <el-button type="danger" text @click="deleteShipyard(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="df aic jcfe mt40 mr20">
      <el-pagination
        background
        layout="prev, pager, next"
        :current-page="currentPage"
        :total="total"
        @current-change="pageChange"
      />
    </div>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="700">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="船厂名称" prop="shipyardName">
          <el-input v-model="formData.shipyardName" class="w400" />
        </el-form-item>
        <el-form-item label="船厂图片" prop="shipyardImgFileKey">
          <Uploader
            :limit="1"
            :file-list="shipyardImgList"
            action-url="/api/file/upload"
            @on-upload-file-list="handleUploadImg"
            @on-remove-file-list="handleRemoveImg"
          />
        </el-form-item>
        <el-form-item label="地址" prop="shipyardAddress">
          <el-input v-model="formData.shipyardAddress" class="w400" />
        </el-form-item>
        <el-form-item label="联系人" prop="contactName">
          <el-input v-model="formData.contactName" class="w400" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="formData.contactPhone" class="w400" />
        </el-form-item>
        <el-form-item label="船坞数量" prop="shipyardDockNum">
          <el-input-number
            v-model="formData.shipyardDockNum"
            :min="0"
            class="w400"
          />
        </el-form-item>
        <el-form-item label="年产能(艘)" prop="shipyardAnnualProdCapacity">
          <el-input-number
            v-model="formData.shipyardAnnualProdCapacity"
            :min="0"
            class="w400"
          />
        </el-form-item>
        <el-form-item label="船厂介绍" prop="shipyardIntroduce">
          <el-input
            v-model="formData.shipyardIntroduce"
            type="textarea"
            :rows="4"
            class="w400"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import api from "../../apis/fetch";
import Uploader from "../../components/Uploader.vue";
import { useStore } from "vuex";

const store = useStore();
const loginAccountId = store.state.loginAccountId;

const searchKey = ref("");
const currentPage = ref(1);
const total = ref(0);
const tableData = ref([]);

const dialogVisible = ref(false);
const dialogTitle = ref("新增船厂");
const formRef = ref(null);
const shipyardImgList = ref([]);

const formData = reactive({
  loginAccountId: loginAccountId,
  shipyardId: 0,
  shipyardName: "",
  shipyardImgFileKey: "",
  shipyardAddress: "",
  contactName: "",
  contactPhone: "",
  shipyardIntroduce: "",
  shipyardDockNum: 0,
  shipyardAnnualProdCapacity: 0,
});

const rules = reactive({
  shipyardName: [
    { required: true, message: "请输入船厂名称", trigger: "blur" },
  ],
  shipyardAddress: [{ required: true, message: "请输入地址", trigger: "blur" }],
  contactName: [{ required: true, message: "请输入联系人", trigger: "blur" }],
  contactPhone: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
  ],
  shipyardDockNum: [
    { required: true, message: "请输入船坞数量", trigger: "blur" },
  ],
  shipyardAnnualProdCapacity: [
    { required: true, message: "请输入年产能", trigger: "blur" },
  ],
});

// 获取船厂列表
async function getShipyardList() {
  try {
    const { data } = await api.getShipyardList({
      loginAccountId: loginAccountId,
      term: searchKey.value,
      currentPage: currentPage.value,
      size: 10,
    });
    if (data.status === 0) {
      tableData.value = data.result;
      total.value = data.total;
    } else {
      tableData.value = [];
      total.value = 0;
      ElMessage.error(data.msg || "获取数据失败");
    }
  } catch (error) {
    ElMessage.error("获取数据失败");
  }
}

// 处理图片上传
const handleUploadImg = ({ response: data }) => {
  if (data.status === 0) {
    formData.shipyardImgFileKey = data.result.key;
    shipyardImgList.value = [
      { viewUrl: data.result.viewUrl, fileKey: data.result.key },
    ];
    ElMessage.success("上传成功");
  } else {
    ElMessage.error(data.msg || "上传失败");
  }
};

// 处理图片删除
const handleRemoveImg = () => {
  formData.shipyardImgFileKey = "";
  shipyardImgList.value = [];
};

// 分页切换
function pageChange(page) {
  currentPage.value = page;
  getShipyardList();
}

// 搜索
function handleSearch() {
  currentPage.value = 1;
  getShipyardList();
}

// 新增
function handleAdd() {
  dialogTitle.value = "新增船厂";
  Object.keys(formData).forEach((key) => {
    if (key !== "shipyardId" && key !== "loginAccountId") {
      if (key === "shipyardDockNum" || key === "shipyardAnnualProdCapacity") {
        formData[key] = 0;
      } else {
        formData[key] = "";
      }
    }
  });
  formData.shipyardId = 0;
  shipyardImgList.value = [];
  dialogVisible.value = true;
}

// 编辑
function handleEdit(row) {
  dialogTitle.value = "修改船厂";
  formData.shipyardId = row.shipyardId;
  formData.shipyardName = row.shipyardName;
  formData.shipyardAddress = row.shipyardAddress;
  formData.contactName = row.contactName;
  formData.contactPhone = row.contactPhone;
  formData.shipyardIntroduce = row.shipyardIntroduce;
  formData.shipyardDockNum = row.shipyardDockNum || 0;
  formData.shipyardAnnualProdCapacity = row.shipyardAnnualProdCapacity || 0;
  formData.shipyardImgFileKey = row.shipyardImgFileKey || "";

  // 设置图片
  shipyardImgList.value = [];
  if (row.shipyardImgFileKey) {
    shipyardImgList.value = [
      {
        fileKey: row.shipyardImgFileKey,
        viewUrl: `/api/file/view?fileKey=${row.shipyardImgFileKey}`,
      },
    ];
  }

  dialogVisible.value = true;
}

// 提交表单
async function submitForm() {
  try {
    await formRef.value.validate();
    const apiMethod =
      formData.shipyardId === 0 ? api.addShipyard : api.updateShipyard;
    const { data } = await apiMethod(formData);
    if (data.status === 0) {
      ElMessage.success("操作成功");
      dialogVisible.value = false;
      getShipyardList();
    } else {
      ElMessage.error(data.message || "操作失败");
    }
  } catch (error) {
    console.error(error);
    ElMessage.error("操作失败");
  }
}

// 删除
function deleteShipyard(row) {
  ElMessageBox.confirm("确认删除该船厂信息？", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      const { data } = await api.deleteShipyard({
        loginAccountId: loginAccountId,
        shipyardId: row.shipyardId,
      });
      if (data.status === 0) {
        ElMessage.success("删除成功");
        getShipyardList();
      } else {
        ElMessage.error(data.message || "删除失败");
      }
    } catch (error) {
      ElMessage.error("删除失败");
    }
  });
}

// 初始化获取数据
getShipyardList();
</script>

<style scoped>
.w300 {
  width: 300px;
}
.w400 {
  width: 400px;
}
.ml10 {
  margin-left: 10px;
}
</style>
