<template>
  <div>
    <div class="container-title">船舶信息</div>
    <div
      class="pl50 pt30 bgf df jcsb pr20"
      v-if="route.name == 'shipOwnerDetail' || route.name == 'shipDetail'"
      style="max-width: 1200px"
    >
      <el-button-group class="mr20" v-if="route.name == 'shipOwnerDetail'">
        <el-button
          v-for="(item, index) in shipInfos"
          :key="item.code"
          @click="currentIndex = index"
          :disabled="!shipInfoDisabled"
          v-show="item.code"
          :type="index == currentIndex ? 'primary' : ''"
        >
          {{ item.shipname || "新增船舶" }}
        </el-button>
      </el-button-group>
      <div></div>
      <div class="df">
        <div class="df" v-if="shipInfos[currentIndex].code">
          <el-button v-if="shipInfoDisabled" type="primary" @click="showUpdate">
            更新船舶基础信息
          </el-button>
          <el-button
            v-if="!shipInfoDisabled"
            type="primary"
            @click="confirmUpdate"
          >
            确认更新
          </el-button>
          <el-button
            v-if="!shipInfoDisabled"
            type="primary"
            @click="cancelUpdate"
          >
            取消更新
          </el-button>
          <el-button
            v-if="route.name == 'shipOwnerDetail'"
            @click="deleteShip(currentIndex)"
            type="primary"
            class="mr20"
          >
            删除当前船舶
          </el-button>
        </div>
        <div class="df" v-if="route.name == 'shipOwnerDetail'">
          <el-button
            v-if="shipInfos.length == 0 || shipInfos[currentIndex].code"
            @click="addShip()"
            type="primary"
          >
            新增船舶
          </el-button>
          <div v-else>
            <el-button
              v-if="shipInfos.length > 1"
              @click="cancelAdd()"
              type="primary"
            >
              取消新增船舶
            </el-button>
          </div>
        </div>
      </div>
    </div>
    <div class="line-container-p24">
      <div class="line">
        <div class="info-line">
          <div class="info-line-title">
            <span class="red">*</span>
            船名
          </div>
          <el-input
            class="info-line-text"
            v-model="shipInfos[currentIndex].shipname"
            :disabled="shipInfoDisabled"
          ></el-input>
          <view class="unit"></view>
        </div>
        <div class="info-line">
          <div class="info-line-title">MMSI</div>
          <el-input
            class="info-line-text"
            v-model="shipInfos[currentIndex].mmsi"
            :disabled="
              shipInfoDisabled ||
              !!shipInfos[currentIndex].code ||
              !!shipInfos[currentIndex].shipId
            "
            @blur="searchShip($event, currentIndex)"
          ></el-input>
        </div>
      </div>
      <div class="line">
        <div class="info-line">
          <div class="info-line-title">
            <span class="red">*</span>
            联系人姓名
          </div>
          <el-input
            class="info-line-text"
            v-model="shipInfos[currentIndex].contentShipOwnerName"
            :disabled="shipInfoDisabled"
          ></el-input>
          <view class="unit"></view>
        </div>
        <div class="info-line">
          <div class="info-line-title">
            <span class="red">*</span>
            联系人手机号
          </div>
          <el-input
            class="info-line-text"
            v-model="shipInfos[currentIndex].contentShipOwnerPhone"
            :disabled="shipInfoDisabled"
          ></el-input>
          <view class="unit"></view>
        </div>
      </div>
      <div class="line">
        <div class="info-line">
          <div class="info-line-title">船长</div>
          <el-input
            class="info-line-text"
            v-model="shipInfos[currentIndex].length"
            :disabled="shipInfoDisabled"
          ></el-input>
          <view class="unit">米</view>
        </div>
        <div class="info-line">
          <div class="info-line-title">船宽</div>
          <el-input
            class="info-line-text"
            v-model="shipInfos[currentIndex].breadth"
            :disabled="shipInfoDisabled"
          ></el-input>
          <view class="unit">米</view>
        </div>
      </div>
      <div class="line">
        <div class="info-line">
          <div class="info-line-title">载货吨位</div>
          <el-input
            class="info-line-text"
            v-model="shipInfos[currentIndex].loadTons"
            :disabled="shipInfoDisabled"
          ></el-input>
          <view class="unit">吨</view>
        </div>
        <div class="info-line">
          <div class="info-line-title">船龄</div>
          <el-input
            class="info-line-text"
            v-model="shipInfos[currentIndex].age"
            :disabled="shipInfoDisabled"
          ></el-input>
          <view class="unit">年</view>
        </div>
      </div>
      <div class="line">
        <div class="info-line">
          <div class="info-line-title">满载吃水</div>
          <el-input
            class="info-line-text"
            v-model="shipInfos[currentIndex].draught"
            :disabled="shipInfoDisabled"
          ></el-input>
          <view class="unit">米</view>
        </div>
        <div class="info-line">
          <div class="info-line-title">吨位(总吨)</div>
          <el-input
            class="info-line-text"
            v-model="shipInfos[currentIndex].tonnage"
            :disabled="shipInfoDisabled"
          ></el-input>
          <view class="unit">吨</view>
        </div>
      </div>
    </div>
    <div style="max-width: 1200px">
      <div class="container-title">船舶证书</div>
      <div
        v-for="(item, index) in shipInfos[currentIndex].shipCerts"
        :key="item.title"
        style="background: #fff"
        class="pt20"
      >
        <div v-if="item.type == 5" class="container-title fs18 pt10 pb10">
          船舶保险
        </div>
        <div class="df aic pl40 pb20">
          <div class="c6 fs16 mr30">{{ item.typeName }}</div>
        </div>
        <div class="ml50 mb20 c7 fs14" v-if="item.type != 0">
          <div
            class="df aic mb10"
            v-for="(item1, index1) in item.certValids"
            :key="item.id"
          >
            <div class="mr10">{{ item1.typeName }}</div>
            <el-date-picker
              style="width: 140px; font-size: 13px"
              v-model="item1.startValidTime"
              @change="changeDate($event, item, item1)"
              type="date"
              placeholder="有效期开始时间"
              value-format="YYYY/MM/DD"
              format="YYYY/MM/DD"
            />
            <div style="margin: 0 4px">-</div>
            <el-date-picker
              style="width: 140px; font-size: 13px"
              v-model="item1.endValidTime"
              @change="changeDate($event, item, item1)"
              type="date"
              placeholder="有效期结束时间"
              value-format="YYYY/MM/DD"
              format="YYYY/MM/DD"
            />
          </div>
        </div>
        <div class="df">
          <Uploader
            class="ml50 pb20"
            :uploaderId="'certsId' + 'country'"
            :params="
              shipInfos[currentIndex].code
                ? {
                    ...updateParams,
                    shipCode: shipInfos[currentIndex].code,
                    type: item.type,
                  }
                : addParams
            "
            :actionUrl="
              shipInfos[currentIndex].code
                ? store.state.updateCertsUrl
                : store.state.addCertsUrl
            "
            :disabled="disabled"
            :fileList="item.certs"
            @onUploadFileList="uploadSuccess($event, index)"
            @onRemoveFileList="removeSuccess($event, index)"
          ></Uploader>
        </div>
      </div>
      <div
        v-if="!shipInfos[currentIndex].code"
        class="p30 mb30 df jcfe"
        style="background: #fff"
      >
        <el-button :loading="isSubmitLoading" @click="submit" type="primary">
          {{ isSubmitLoading ? "正在添加" : "添加船舶" }}
        </el-button>
      </div>
    </div>
  </div>
</template>
<script setup>
import { defineComponent, computed, ref, onMounted, watch } from "vue";
import { ElMessage } from "element-plus";
import api from "../apis/fetch";
import _ from "lodash";
import store from "../store";
import { useRoute } from "vue-router";
import router from "../router";
const route = useRoute();
const props = defineProps({
  certsId: {
    type: String,
    default: "cert",
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  shipInfos: {
    type: Array,
    default: [{}],
  },
  shipOwnerId: [String, Number],
});
let currentIndex = ref(0);
const emit = defineEmits(["submit"]);

function initCerts(certs) {
  console.log(certs);
}
let updateParams = ref({
  loginAccountId: localStorage.loginAccountId,
});
let addParams = ref({
  loginAccountId: localStorage.loginAccountId,
});

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

async function changeDate(e, item, item1) {
  if (props.shipInfos[currentIndex.value].code) {
    let { data } = await api.updateShipCertValid({
      shipCode: props.shipInfos[currentIndex.value].code,
      type: item.type,
      validType: item1.type,
      startValidTime: item1.startValidTime,
      endValidTime: item1.endValidTime,
    });
    if (data.status == 0) {
      ElMessage({
        message: "更新成功!",
        type: "success",
      });
    }
  }
}

function getShipCerts() {
  return shipCerts.value;
}

async function searchShip(e) {
  if (e.target.value.length != 9) return;
  const loading = ElLoading.service({
    lock: true,
    text: "正在匹配船舶...",
    background: "rgba(0, 0, 0, 0.7)",
  });
  let { data } = await api.searchShip({
    mmsi: e.target.value,
  });
  loading.close();
  if (data.status == 0) {
    data.result.shipCerts[0].typeName = "船舶主要项目页";
    data.result.shipCerts[1].typeName = "船舶国籍证书";
    data.result.shipCerts[2].typeName = "内河船舶适航证书";
    data.result.shipCerts[3].typeName = "船舶营运证书";
    data.result.shipCerts[4].typeName = "内河船舶最低安全配员证书";
    data.result.shipCerts[5].typeName = "船舶保险";
    for (let i of data.result.shipCerts) {
      for (let j of i.certs) {
        j.url = j.viewUrl;
      }
    }
    data.result.disabled = false;
    if (props.shipInfos[currentIndex.value].shipname)
      data.result.shipname = props.shipInfos[currentIndex.value].shipname;

    props.shipInfos[currentIndex.value] = data.result;
  }
}
function deleteShip(index) {
  ElMessageBox.confirm("确认删除船舶?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      console.log(index);
      let { data } = await api.deleteShip({
        shipCode: props.shipInfos[index].code,
      });
      if (data.status == 0) {
        ElMessage({
          type: "success",
          message: "删除成功",
        });
        props.shipInfos.splice(index, 1);
        currentIndex.value = 0;
      }
    })
    .catch(() => {});
}
let cacheIndex = -1;
async function addShip(item) {
  cacheIndex = _.cloneDeep(currentIndex.value);
  shipInfoDisabled.value = false;
  let { data } = await api.getAddShipCerts({});
  let initShipInfo = {
    shipId: 0,
    disabled: false,
    shipCerts: data.result,
  };
  if (
    props.shipInfos.length &&
    props.shipInfos[props.shipInfos.length - 1].code
  ) {
    props.shipInfos.push(initShipInfo);
  } else {
    props.shipInfos[props.shipInfos.length - 1] = initShipInfo;
  }
  currentIndex.value = props.shipInfos.length - 1;
}
function cancelAdd() {
  currentIndex.value = _.cloneDeep(cacheIndex);
  shipInfoDisabled.value = true;
}
let isSubmitLoading = ref(false);
async function submit() {
  if (!props.shipInfos[currentIndex.value].shipname) {
    ElMessage({
      type: "warning",
      message: "请填写船舶名称",
    });
    return;
  }
  if (!props.shipInfos[currentIndex.value].contentShipOwnerName) {
    ElMessage({
      type: "warning",
      message: "请填写联系人姓名",
    });
    return;
  }
  if (!props.shipInfos[currentIndex.value].contentShipOwnerPhone) {
    ElMessage({
      type: "warning",
      message: "请填写联系人手机号",
    });
    return;
  }
  isSubmitLoading.value = true;
  let res = await api.addShip({
    ...props.shipInfos[currentIndex.value],
    shipOwnerId: props.shipOwnerId,
  });
  isSubmitLoading.value = false;
  store.commit("removeAlive", "shipOwnerList");
  router.replace("/shipOwnerManage/shipOwnerList");
}

let shipInfoDisabled = ref(true);
let cacheInfo = ref({});
function showUpdate() {
  cacheInfo.value = _.cloneDeep(props.shipInfos[currentIndex.value]);
  shipInfoDisabled.value = false;
}
async function confirmUpdate() {
  let postData = props.shipInfos[currentIndex.value];
  postData.shipCode = postData.code;
  let { data } = await api.updateShip(postData);
  if (data.status == 0) {
    ElMessage({
      message: data.msg,
      type: "success",
    });
    shipInfoDisabled.value = true;
  } else {
    ElMessage({
      message: data.msg,
      type: "error",
    });
  }
}
function cancelUpdate() {
  props.shipInfos[currentIndex.value] = _.cloneDeep(cacheInfo.value);
  shipInfoDisabled.value = true;
}

function changeDisable(b) {
  shipInfoDisabled.value = b;
}
defineExpose({
  initCerts,
  getShipCerts,
  changeDisable,
});
onMounted(() => {});
</script>

<style scoped>
.unit {
  width: 40px;
  text-align: center;
  color: #555;
}
</style>
