<template>
  <div class="full-container-p24">
    <div class="mb20" style="margin-left: 200px">
      <el-button-group class="mr30">
        <el-button
          :type="type == 2 ? 'primary' : ''"
          @click="(currentPage = 1), (type = 2), getCertList()"
        >
          {{ nextMonthStr }}
        </el-button>
        <el-button
          :type="type == 8 ? 'primary' : ''"
          @click="(currentPage = 1), (type = 8), getCertList()"
        >
          {{ nextNextMonthStr }}
        </el-button>
        <el-button
          :type="type == 9 ? 'primary' : ''"
          @click="(currentPage = 1), (type = 9), getCertList()"
        >
          {{ nextNextNextMonthStr }}
        </el-button>

        <el-button
          :type="type == 0 ? 'primary' : ''"
          @click="(currentPage = 1), (type = 0), getCertList()"
        >
          已过期
        </el-button>
        <el-button
          :type="type == 3 ? 'primary' : ''"
          @click="(currentPage = 1), (type = 3), getCertList()"
        >
          全部
        </el-button>
      </el-button-group>
    </div>
    <div class="df">
      <div class="btns mr20 mt50">
        <div v-for="(item, index) in certTypes" :key="item.id">
          <el-button
            :type="certType == item.type ? 'primary' : ''"
            @click="
              (currentPage = 1),
                (certType = item.type),
                (currentTypeIndex = index),
                (validType = 1);
              getCertList();
            "
            class="btn"
          >
            {{ item.typeName }}
          </el-button>
        </div>
      </div>
      <div>
        <el-select
          style="width: 240px"
          v-if="currentTypeIndex == 1"
          v-model="validType"
          @change="changeSelect"
          class="mb10 tac"
          placeholder="有效期类型"
        >
          <el-option
            v-for="item in certTypes[currentTypeIndex].validTypes"
            :key="item.type"
            :label="item.typeName"
            :value="item.type"
          />
        </el-select>
        <el-table border :data="tableData" stripe style="width: 900px">
          <el-table-column
            align="center"
            type="index"
            label="序号"
            width="80"
          />
          <el-table-column
            align="center"
            prop="shipname"
            label="船名"
            min-width="120"
          />
          <el-table-column
            align="center"
            prop="shipRegistryProvince"
            label="船籍"
            min-width="80"
          />
          <el-table-column
            v-if="certType == 6"
            align="center"
            prop="crewName"
            label="船员姓名"
            min-width="120"
          />
          <el-table-column
            v-if="certType != 6"
            align="center"
            prop="shipOwnerName"
            label="船员姓名"
            min-width="120"
          />
          <el-table-column
            v-if="certType != 6"
            align="center"
            prop="shipOwnerPhone"
            label="手机号"
            min-width="140"
          />
          <el-table-column
            align="center"
            prop="endValidTime"
            label="有效期"
            min-width="120"
          >
            <template v-slot="scope">
              {{ subTimeStr(scope.row.endValidTime) }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="160">
            <template #default="scope">
              <div v-if="certType == 6">
                <el-button
                  type="primary"
                  text
                  @click="goToShipOwnerDetail(scope.row.id)"
                >
                  详情
                </el-button>
                <el-button type="primary" text @click="handleEdit(scope.row)">
                  更新
                </el-button>
              </div>
              <div v-else>
                <el-button
                  type="primary"
                  text
                  @click="goToShipDetail(scope.row.shipCode)"
                >
                  详情
                </el-button>
                <el-button type="primary" text @click="handleEdit(scope.row)">
                  更新
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="df aic jcfe mt40 mr20">
          <el-pagination
            :current-page="currentPage"
            @current-change="pageChange"
            background
            layout="prev, pager, next"
            :total="total"
          />
        </div>
      </div>
      <el-dialog :title="dialogTypeName" v-model="ruleFormVisible" width="800">
        <el-form
          class="pt20"
          ref="ruleFormRef"
          :model="ruleForm"
          label-width="120px"
        >
          <el-form-item :label="ruleForm.typeName" v-if="dialogType != 6">
            <el-date-picker
              style="width: 140px; font-size: 13px"
              v-model="ruleForm.startValidTime"
              type="date"
              placeholder="有效期开始时间"
              value-format="YYYY/MM/DD"
              format="YYYY/MM/DD"
            />
            <div style="margin: 0 10px">-</div>
            <el-date-picker
              style="width: 140px; font-size: 13px"
              v-model="ruleForm.endValidTime"
              type="date"
              placeholder="有效期结束时间"
              value-format="YYYY/MM/DD"
              format="YYYY/MM/DD"
            />
          </el-form-item>
          <div v-if="dialogType == 6">
            <el-row :gutter="20">
              <el-col :span="10">
                <el-form-item label="船员姓名">
                  {{ ruleForm.fullName }}
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="10">
                <el-form-item label="船员性别" prop="gender">
                  <el-select
                    v-model="ruleForm.gender"
                    placeholder="请选择"
                    class="w300"
                  >
                    <el-option label="男" :value="1"></el-option>
                    <el-option label="女" :value="2"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="证书编号" prop="certNo">
                  <el-input
                    v-model="ruleForm.certNo"
                    placeholder="请输入"
                    class="w300"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="10">
                <el-form-item label="专业类别" prop="majorId">
                  <el-select
                    v-model="ruleForm.majorId"
                    placeholder="请选择专业类别"
                    class="w300"
                    @change="handleMajorChange($event, 1)"
                  >
                    <el-option
                      v-for="item in certTypeOptions"
                      :key="item.key"
                      :label="item.value"
                      :value="item.key"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="证书类别" prop="categoryId">
                  <el-select
                    v-model="ruleForm.categoryId"
                    placeholder="请选择证书类别"
                    class="w300"
                    @change="handleCategoryChange($event, 1)"
                  >
                    <el-option
                      v-for="item in categoryOptions"
                      :key="item.key"
                      :label="item.value"
                      :value="item.key"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="10">
                <el-form-item label="职务类别" prop="postId">
                  <el-select
                    v-model="ruleForm.postId"
                    placeholder="请选择职务类别"
                    class="w300"
                    @change="handlePostChange"
                  >
                    <el-option
                      v-for="item in postOptions"
                      :key="item.key"
                      :label="item.value"
                      :value="item.key"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="10">
                <el-form-item label="发证日期" prop="issuerAt">
                  <el-date-picker
                    v-model="ruleForm.issuerAt"
                    type="date"
                    placeholder="选择日期"
                    format="YYYY-MM-DD"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="截止日期" prop="expiryAt">
                  <el-date-picker
                    v-model="ruleForm.expiryAt"
                    type="date"
                    placeholder="选择日期"
                    format="YYYY-MM-DD"
                    class="w300"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="10">
                <el-form-item label="签发机构" prop="issuerAuthority">
                  <el-input
                    v-model="ruleForm.issuerAuthority"
                    placeholder="请输入"
                    class="w300"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="16">
                <el-form-item label="适用限制">
                  <el-input
                    type="textarea"
                    v-model="ruleForm.applicableRestrictions"
                    :rows="4"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <el-form-item label="证书图片">
            <div class="df">
              <Uploader
                class="pb20"
                :uploaderId="'certsId' + 'country'"
                :params="dialogType === 6 ? shipOwnerParams : shipParams"
                :actionUrl="
                  dialogType === 6
                    ? store.state.shipOwnerUpdateUrl
                    : store.state.shipCertUpdateUrl
                "
                :fileList="dialogType === 6 ? certFiles : certs"
                @onUploadFileList="uploadSuccess($event)"
                @onRemoveFileList="removeSuccess($event)"
              ></Uploader>
            </div>
          </el-form-item>
          <el-form-item label="办理方式">
            <el-radio-group
              v-model="ruleForm.processMethod"
              @change="handleProcessMethodChange"
            >
              <el-radio :value="1">自办</el-radio>
              <el-radio :value="2">代办</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="证书代办机构"
            v-if="ruleForm.processMethod === 2"
          >
            <RemoteSelect
              class="w300"
              api="getCertServAuthSelect"
              v-model="ruleForm.certServAuthName"
              placeholder="请选择"
              @selectItem="selectCertServer($event)"
            ></RemoteSelect>
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              class="w300"
              type="textarea"
              :rows="5"
              v-model="ruleForm.processRemark"
              placeholder="请填写"
            ></el-input>
          </el-form-item>
        </el-form>
        <div class="df aic jcc mt50 pb20">
          <el-button type="primary" @click="submit">提交</el-button>
          <el-button @click="ruleFormVisible = false">取消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script setup>
import { ref, h, reactive, toRefs, onMounted } from "vue";
import { ElNotification, ElMessageBox, ElMessage } from "element-plus";
import store from "../../store";
import router from "../../router";
import md5 from "md5";
import api from "../../apis/fetch";
import { useRoute } from "vue-router";
import _ from "lodash";
import { subTimeStr } from "../../utils/utils";

const route = useRoute();
let type = ref(2);
let certType = ref(1);
let tableData = ref([]);
let total = ref(0);
let currentPage = ref(1);
const monthNames = [
  "一月",
  "二月",
  "三月",
  "四月",
  "五月",
  "六月",
  "七月",
  "八月",
  "九月",
  "十月",
  "十一月",
  "十二月",
];

function getMonthName(monthOffset) {
  const currentMonth = new Date().getMonth();
  const newMonth = (currentMonth + monthOffset) % 12;
  return monthNames[newMonth] + "到期";
}

const nextMonthStr = ref(getMonthName(1));
const nextNextMonthStr = ref(getMonthName(2));
const nextNextNextMonthStr = ref(getMonthName(3));
async function getCertList() {
  const loading = ElLoading.service({
    lock: true,
    text: "正在获取数据...",
    background: "rgba(0, 0, 0, 0.7)",
  });
  let { data } = await api.getCertList({
    type: type.value,
    certType: certType.value,
    validType: validType.value,
    currentPage: currentPage.value,
    size: 10,
  });
  loading.close();
  if (data.status == 0) {
    total.value = data.total;
    tableData.value = data.result;
  } else {
    total.value = 0;
    tableData.value = [];
  }
}
function pageChange(e) {
  currentPage.value = e;
  getCertList();
}
function goToShipDetail(shipCode) {
  router.push({
    path: "/shipManage/shipDetail",
    query: {
      shipCode,
    },
  });
}

function goToShipOwnerDetail(shipOwnerId) {
  router.push({
    path: "/shipOwnerManage/shipOwnerDetail",
    query: {
      shipOwnerId,
    },
  });
}

let certTypes = ref([
  {
    validTypes: [],
  },
]);
async function getCertListType() {
  let { data } = await api.getCertListType({});
  certTypes.value = data.result.filter((item) => {
    return item.typeName != "船舶保险";
  });
}

let currentTypeIndex = ref(0);
let validType = ref(1);
function changeSelect(e) {
  validType.value = e;
  getCertList();
}
const ruleFormVisible = ref(false);
const ruleFormRef = ref(null);
const certTypeOptions = ref([]); // 专业类别选项
const categoryOptions = ref([]); // 证书类别选项
const postOptions = ref([]); // 职务类别选项
const certTypeData = ref([]); // 存储完整的证书类型数据

const ruleForm = ref({
  gender: "",
  certNo: "",
});
const certs = ref([]);
const certFiles = ref([]);
const dialogType = ref(0);
const dialogTypeName = ref("");
const shipParams = ref({});
const shipOwnerParams = ref({ type: 1 });
async function handleEdit(row) {
  const postData = {
    certType: certType.value,
  };
  if (certType.value == 6) {
    postData["shipOwnerId"] = row.id;
    ruleForm.value.shipOwnerId = row.id;
    shipOwnerParams.value.shipOwnerId = row.id;
  } else {
    postData["certValidityPeriodId"] = row.id;
    ruleForm.value.certValidityPeriodId = row.id;
    shipParams.value.shipCode = row.shipCode;
  }
  ruleFormVisible.value = true;
  let { data } = await api.getCertProcessDetail(postData);
  dialogType.value = data.result.type;
  dialogTypeName.value = data.result.typeName;
  ruleForm.value.processMethod = 1;
  ruleForm.value.certServAuthId = "";
  ruleForm.value.certServAuthName = "";
  ruleForm.value.processRemark = "";

  if (data.result.type === 6) {
    Object.assign(ruleForm.value, data.result.certDetail);
    certFiles.value = data.result.certFiles;
    if (ruleForm.value.majorId) {
      handleMajorChange(ruleForm.value.majorId);
      if (ruleForm.value.categoryId) {
        handleCategoryChange(ruleForm.value.categoryId);
      }
    }
  } else {
    Object.assign(ruleForm.value, data.result.certValids[0]);
    certs.value = data.result.certs;
    shipParams.value.type = data.result.type;
  }
}

function uploadSuccess({ response, file, list }, index) {
  if (response.status == 0) {
    let { key, fileKey, viewUrl, downloadUrl, id } = response.result;
    let data = {
      fileKey: fileKey || key,
      viewUrl,
      downloadUrl,
      id,
      url: viewUrl,
    };
    if (dialogType.value === 6) {
      certFiles.value.push(data);
    } else {
      certs.value.push(data);
    }
  }
}
async function removeSuccess({ file, fileIndex }) {
  let { data } = await api[
    dialogType.value === 6 ? "deleteShipOwnerCert" : "deleteShipCert"
  ]({ [dialogType.value === 6 ? "docId" : "shipCertId"]: file.id });
  if (data.status == 0) {
    ElMessage({
      message: "删除成功!",
      type: "success",
    });
    if (dialogType.value === 6) {
      certFiles.value.splice(fileIndex, 1);
    } else {
      certs.value.splice(fileIndex, 1);
    }
  }
}

function handleProcessMethodChange(value) {
  if (value === 1) {
    // 自办时清空代办机构
    ruleForm.value.certServAuthId = "";
    ruleForm.value.certServAuthName = "";
  }
}

const handleMajorChange = (majorId, isChange) => {
  if (isChange) {
    ruleForm.value.categoryId = "";
    ruleForm.value.postId = "";
  }
  const selectedMajor = certTypeData.value.find((item) => item.key === majorId);
  if (selectedMajor && selectedMajor.children) {
    categoryOptions.value = selectedMajor.children.map((item) => ({
      key: item.key,
      value: item.value,
    }));
  } else {
    categoryOptions.value = [];
  }
  postOptions.value = [];
};

const handleCategoryChange = (categoryId, isChange) => {
  if (isChange) {
    ruleForm.value.postId = "";
  }
  const selectedMajor = certTypeData.value.find(
    (item) => item.key === ruleForm.value.majorId
  );
  if (selectedMajor && selectedMajor.children) {
    const selectedCategory = selectedMajor.children.find(
      (item) => item.key === categoryId
    );
    if (selectedCategory && selectedCategory.children) {
      postOptions.value = selectedCategory.children.map((item) => ({
        key: item.key,
        value: item.value,
      }));
    } else {
      postOptions.value = [];
    }
  } else {
    postOptions.value = [];
  }
};

function handlePostChange() {}

const getCertTypeData = async () => {
  try {
    const { data } = await api.getShipOwnerCertTypeSelect();
    if (data.status === 0 && data.result) {
      certTypeData.value = data.result;
      certTypeOptions.value = data.result.map((item) => ({
        key: item.key,
        value: item.value,
      }));
    } else {
      ElMessage.error(data.msg || "获取证书类型数据失败");
    }
  } catch (error) {
    console.error("获取证书类型数据出错:", error);
    ElMessage.error("获取证书类型数据出错");
  }
};

function selectCertServer(e) {
  console.log(e);
  if (e && e.value) {
    ruleForm.value.certServAuthId = e.value;
    ruleForm.value.certServAuthName = e.key;
  } else {
    ruleForm.value.certServAuthId = "";
    ruleForm.value.certServAuthName = "";
  }
}

async function submit() {
  console.log(ruleForm.value);
  let { data } = await api[
    dialogType.value === 6 ? "saveShipOwnerProcess" : "saveShipProcess"
  ](ruleForm.value);
}

onMounted(() => {
  getCertList();
  getCertListType();
  getCertTypeData();
});
</script>

<style scoped>
.btn {
  height: 50px;
  width: 180px;
  border-radius: 0;
}

.w300 {
  width: 300px !important;
}
</style>
