<template>
  <div class="card">
    <div class="df aic jcsb mb10">
      <div class="t20">招标信息</div>
      <div class="df aic">
        <div
          class="mr10 fs18"
          :style="{ color: tenderData.status === 1 ? '#00B050' : '#FFA500' }"
        >
          {{ tenderData.status === 1 ? "招标中" : "" }}
          {{ tenderData.status === 2 ? "招标完成" : "" }}
          {{ tenderData.status === 3 ? "取消招标" : "" }}
        </div>
        <div class="mr10" v-if="tenderData.status === 1">
          竞标截止剩余: {{ getLeftTime(tenderData.bidDeadlineDatetime) }}
        </div>
      </div>
    </div>
    <div class="card mb20">
      <div class="df aic mb10">
        <div class="info-title">发起时间:</div>
        <div class="info-text">{{ tenderData.operatorDate }}</div>
        <div class="info-title">货种:</div>
        <div class="info-text">{{ tenderData.cargo }}</div>
        <div class="info-title">装货港:</div>
        <div class="info-text">{{ tenderData.loadPortName }}</div>
      </div>
      <div class="df aic mb10">
        <div class="info-title">截止时间:</div>
        <div class="info-text">{{ tenderData.bidDeadlineDatetime }}</div>
        <div class="info-title">发货吨位:</div>
        <div class="info-text">{{ tenderData.tons }} 吨</div>
        <div class="info-title">卸货港:</div>
        <div class="info-text">{{ tenderData.dischargePortName }}</div>
      </div>
    </div>
    <div v-if="tenderData.initMethod === 3">
      <div class="t20 mb10">前置航次信息</div>
      <div class="card">
        <AMapContainer
          :ships="[voyage]"
          :loadPorts="loadPorts"
          :dischargePorts="dischargePorts"
          style="width: 100%; height: 500px"
        ></AMapContainer>
        <div class="card mt10">
          <div class="t16 mb10">航次信息</div>
          <div class="df aic mb10">
            <div class="info-title">船名:</div>
            <div class="info-text">{{ voyage.shipName }}</div>
            <div class="info-title">装货港:</div>
            <div class="info-text">{{ voyage.loadPort }}</div>
            <div class="info-title">货种:</div>
            <div class="info-text">{{ voyage.cargo }}</div>
          </div>
          <div class="df aic mb10">
            <div class="info-title">MMSI:</div>
            <div class="info-text">{{ voyage.mmsi }}</div>
            <div class="info-title">卸货港:</div>
            <div class="info-text">{{ voyage.dischargePorts }}</div>
            <div class="info-title">装载吨位:</div>
            <div class="info-text">{{ voyage.tons }} 吨</div>
          </div>
        </div>
      </div>
    </div>
    <div class="t20 mt20 mb10">运力要求</div>
    <div class="card">
      <pre style="white-space: pre-wrap">{{
        tenderData.capacityRequirements
      }}</pre>
    </div>
    <div class="t20 mt20 mb10">报价要求</div>
    <div class="card">
      <pre style="white-space: pre-wrap">{{ tenderData.quotationRequest }}</pre>
    </div>
    <el-divider></el-divider>
    <div class="t20 mb10">投标信息</div>
    <div class="df aic mb10">
      <div class="mr10">参与竞标公司数量:</div>
      <div class="mr20">{{ tenderData.participateProxyNum }}</div>
      <el-button
        v-if="tenderData.status === 1"
        size="small"
        type="primary"
        @click="showAddTenderCompany()"
      >
        增加竞标公司
      </el-button>
      <el-dialog v-model="isAddProxyCompanyVisible" title="增加竞标公司">
        <div class="df aic mb10">
          <div class="red">*</div>
          <div>请选择新代理公司(可多选):</div>
          <el-select
            class="w300 ml20"
            v-model="currentProxyCompanies"
            value-key="id"
            placeholder="请选择参与竞标代理公司"
            multiple
            clearable
            @change="proxyCompaniesChange"
          >
            <el-option
              v-for="item in proxyCompanies"
              :key="item.id"
              :label="item.companyName"
              :value="item"
            ></el-option>
          </el-select>
        </div>
        <el-table
          v-if="currentProxyCompanies.length > 0"
          :data="currentProxyCompanies"
          border
          stripe
        >
          <el-table-column label="公司名称" prop="companyName" />
          <el-table-column label="联系人" prop="contactName" />
          <el-table-column label="手机号" prop="contactPhone" />
          <el-table-column label="邮箱" prop="contactEmail" />
          <el-table-column label="操作" width="80">
            <template #default="scope">
              <el-button type="danger" @click="remove(scope)" size="small">
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="df aic jcfe mt20 pr20">
          <el-button @click="cancelAddTenderCompany()">取消</el-button>

          <el-button type="primary" @click="addTenderProxy()">
            确定添加
          </el-button>
        </div>
      </el-dialog>
    </div>
    <div class="df aic mb10">
      <div class="mr10">未参与竞标公司数量:</div>
      <div class="mr20">{{ tenderData.notCompleteBidProxyNum }}</div>
      <div class="mr10">完成竞标公司数量:</div>
      <div class="mr20">{{ tenderData.completeBidProxyNum }}</div>
    </div>

    <div class="card mb30" v-for="(item, index) in tenderData.tenderProxies">
      <div class="df aic jcsb mb10">
        <div>{{ item.proxyCompanyName }}</div>
        <div class="df aic" v-if="tenderData.status === 1">
          <div class="mr10">邮件通知状态:</div>
          <div
            class="mr10 fs18"
            :style="{
              color: item.emailSendStatus === 0 ? '#9d0016' : '#00B050',
            }"
          >
            {{ item.emailSendStatus === 0 ? "未发送" : "" }}
            {{ item.emailSendStatus === 1 ? "已发送" : "" }}
          </div>

          <el-button
            v-if="item.emailSendStatus === 0"
            size="small"
            type="primary"
          >
            发送
          </el-button>
          <el-button
            v-if="item.emailSendStatus === 1"
            size="small"
            type="primary"
          >
            再次发送
          </el-button>
        </div>
      </div>
      <div v-if="item.bidStatus !== 2">
        <AMapContainer
          :mapId="'map' + index"
          :ships="item.tenderProxyBids"
          style="height: 300px"
          class="mb10"
        ></AMapContainer>
        <el-table
          :data="item.tenderProxyBids"
          border
          stripe
          show-summary
          :summary-method="getSummaries"
        >
          <el-table-column label="船名" prop="shipName"></el-table-column>
          <el-table-column label="MMSI" prop="shipMmsi"></el-table-column>
          <el-table-column label="装载吨位" prop="loadTons"></el-table-column>
          <el-table-column
            label="报价(元/吨)"
            prop="quotePrice"
          ></el-table-column>
          <el-table-column
            label="预计运费(元,单船)"
            prop="estimatedCost"
          ></el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <div class="df aic jcc" v-if="tenderData.status === 1">
                <el-button
                  v-if="scope.row.status === 1"
                  size="small"
                  type="primary"
                  @click="selectTenderShip(scope.row, 1)"
                >
                  选择中标
                </el-button>
                <el-button
                  v-if="scope.row.status === 2"
                  size="small"
                  type="danger"
                  @click="selectTenderShip(scope.row, 2)"
                >
                  取消中标
                </el-button>
              </div>

              <el-tag
                type="success"
                v-if="scope.row.status === 2 && tenderData.status === 2"
              >
                已中标
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-else>
        <el-result
          class="card"
          icon="error"
          title="放弃竞标"
          :sub-title="item.giveUpRemark"
        ></el-result>
      </div>
    </div>

    <div v-if="tenderData.status === 1" class="df aic jcfe mt30">
      <div>
        <el-button type="default" @click="completeTender(2)">
          取消招标
        </el-button>
        <el-button type="primary" @click="completeTender(1)">
          完成招标
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import api from "../../apis/fetch";
import store from "../../store";
import router from "../../router";
import { ref, onMounted, reactive, computed } from "vue";
import { ElNotification, ElMessage, ElMessageBox } from "element-plus";
import { mapGetters } from "vuex";
import { useRoute } from "vue-router";

const route = useRoute();

const tenderData = ref({
  operatorDate: "",
  bidDeadlineDatetime: "",
  cargo: "",
  loadPortName: "",
  tons: "",
  dischargePortName: "",
  participateProxyNum: "",
  capacityRequirements: "",
  quotationRequest: "",
  tenderProxies: [],
});

const voyage = ref({
  // shipName: "航次船舶",
  // loadPort: "武汉",
  // cargo: "豆粕",
  // mmsi: "998221222",
  // dischargePorts: "北仑",
  // tons: 5000,
  // longitude: 120.487381,
  // latitude: 32.042158,
});

const tenderTableData = ref([]);

const getSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "预估总运费";
      return;
    }
    const values = data.map((item) => Number(item[column.property]));
    if (index == 4) {
      sums[index] = `${values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!Number.isNaN(value)) {
          return prev + curr;
        } else {
          return prev;
        }
      }, 0)} 元`;
    }
  });

  return sums;
};

const loadPorts = ref([]);
const dischargePorts = ref([]);

async function getTenderDetail() {
  let { data } = await api.getTenderDetail({
    tenderId: route.query.id,
  });
  if (data.status === 0) {
    tenderData.value = data.result;
    for (let i of tenderData.value.tenderProxies) {
      for (let j of i.tenderProxyBids) {
        j.estimatedCost = j.loadTons * j.quotePrice;
      }
    }
  } else {
    tenderData.value = {
      operatorDate: "",
      bidDeadlineDatetime: "",
      cargo: "",
      loadPortName: "",
      tons: "",
      dischargePortName: "",
      participateProxyNum: "",
      capacityRequirements: "",
      quotationRequest: "",
      tenderProxies: [],
    };
  }
}

function getLeftTime(givenTime = "2099-12-31 23:59:59") {
  givenTime = new Date(givenTime);
  const currentTime = new Date();

  // 检查当前时间是否超出了截止时间
  if (currentTime > givenTime) {
    return "已超过截止时间";
  }

  const differenceInMilliseconds = Math.abs(givenTime - currentTime);
  const days = Math.floor(differenceInMilliseconds / (1000 * 60 * 60 * 24));
  const hours = Math.floor(
    (differenceInMilliseconds % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
  );
  return `${days}天${hours}小时`;
}

const isAddProxyCompanyVisible = ref(false);
const proxyCompanies = ref([]);

async function getTenderProxySelect() {
  let { data } = await api.getTenderProxySelect({
    cargoId: tenderData.value.cargoId,
  });
  if (data.status === 0) {
    proxyCompanies.value = data.result.filter(
      (item) =>
        !tenderData.value.tenderProxies.some(
          (item1) => item.id === item1.proxyCompanyId
        )
    );
  } else {
    proxyCompanies.value = [];
  }
}
const currentProxyCompanies = ref([]);

function proxyCompaniesChange(e) {
  currentProxyCompanies.value = e;
}

function remove(scope) {
  currentProxyCompanies.value.splice(scope.$index, 1);
}

function showAddTenderCompany() {
  isAddProxyCompanyVisible.value = true;
  getTenderProxySelect();
}

function cancelAddTenderCompany() {
  currentProxyCompanies.value = [];
  isAddProxyCompanyVisible.value = false;
}
async function addTenderProxy() {
  if (currentProxyCompanies.value.length === 0) {
    ElMessage({
      type: "warning",
      message: "请选择代理公司!",
    });
    return;
  }

  let { data } = await api.addTenderProxy({
    tenderId: route.query.id,
    proxyCompanyIds: currentProxyCompanies.value
      .map((item) => item.id)
      .join(","),
  });
  if (data.status === 0) {
    ElNotification({
      type: "success",
      message: "添加成功!",
    });
    getTenderDetail();
  } else {
    ElNotification({
      type: "error",
      message: data.msg,
    });
  }
  cancelAddTenderCompany();
}
function completeTender(status) {
  ElMessageBox.confirm(`确认${status === 2 ? "取消" : "完成"}招标?`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    let { data } = await api.completeTender({
      tenderId: route.query.id,
      status,
    });
    if (data.status === 0) {
      ElNotification({
        type: "success",
        message: `${status === 2 ? "取消" : "完成"}成功!`,
      });
    } else {
      ElNotification({
        type: "error",
        message: data.msg,
      });
    }
    getTenderDetail();
  });
}

function selectTenderShip(row, status) {
  ElMessageBox.confirm(
    `确认${status === 1 ? "选择" : "取消"}${row.shipName}中标?`,
    "提示",
    {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(async () => {
    let { data } = await api.selectTenderShip({
      tenderId: route.query.id,
      status,
      tenderProxyBidId: row.id,
    });
    if (data.status === 0) {
      ElNotification({
        type: "success",
        message: `${status === 1 ? "选择" : "取消"}成功!`,
      });
      getTenderDetail();
    } else {
      ElNotification({
        type: "error",
        message: data.msg,
      });
      console.log(data);
    }
  });
}
onMounted(() => {
  getTenderDetail();
});
</script>

<style scoped>
.info-title {
  width: 110px;
  text-align: right;
  color: #666;
  margin-right: 10px;
}

.info-text {
  width: 160px;
  color: #333;
}
.table-title {
  color: #666;
  margin-right: 10px;
}
.table-text {
  color: #333;
  margin-right: 30px;
}
</style>
