<template>
  <div class="line-container-p24">
    <i class="el-icon-arrow-left"></i>
    <div
      class="dib go-back ml8"
      @click="router.replace('/agencyManage/agencyCompanyList')"
    >
      返回代理公司列表
    </div>
  </div>
  <div class="container-title">代理信息</div>
  <div class="line-container-p24">
    <div class="df aic">
      <div class="normal-label">代理名称</div>
      <el-input
        style="width: 220px; margin-right: 20px"
        :disabled="!isBasicInfoEdit"
        v-model="proxyName"
      ></el-input>
      <div class="normal-label">代理名称缩写</div>
      <el-input
        style="width: 220px; margin-right: 20px"
        :disabled="!isBasicInfoEdit"
        v-model="shortName"
      ></el-input>
      <el-button v-if="!isBasicInfoEdit" @click="editBasicInfo" type="primary">
        修改
      </el-button>
      <el-button
        v-if="isBasicInfoEdit"
        @click="submitBasicInfoEdit"
        type="primary"
      >
        提交
      </el-button>
      <el-button v-if="isBasicInfoEdit" @click="cancelBasicInfoEdit">
        取消
      </el-button>
    </div>
    <div class="df aic mt20">
      <div class="normal-label">联系人</div>
      <el-input
        style="width: 220px; margin-right: 20px"
        :disabled="true"
        v-model="contactName"
      ></el-input>
      <div class="normal-label">联系人手机号</div>
      <el-input
        style="width: 220px; margin-right: 20px"
        :disabled="true"
        v-model="contactPhone"
      ></el-input>
    </div>
    <div class="df aic mt20">
      <div class="normal-label">过期时间</div>
      <el-date-picker
        v-model="expiredTime"
        class="mr20"
        type="datetime"
        format="YYYY/MM/DD"
        value-format="YYYY/MM/DD"
        placeholder="过期时间"
        :disabled="!expiredTimeEditable"
      ></el-date-picker>
      <el-button
        v-if="!expiredTimeEditable"
        @click="editExpiredTime"
        type="primary"
      >
        修改
      </el-button>
      <el-button
        v-if="expiredTimeEditable"
        @click="submitExpiredTime"
        type="primary"
      >
        提交
      </el-button>
      <el-button v-if="expiredTimeEditable" @click="cancelExpiredTime">
        取消
      </el-button>
    </div>
  </div>
  <div class="container-title">子账号信息</div>
  <div class="line-container-p24">
    <div style="display: flex; justify-content: space-between">
      <div style="display: flex">
        <el-input
          placeholder="请输入代理子账户/手机号"
          prefix-icon="el-icon-search"
          v-model="term"
          clearable
          style="height: 32px; width: 330px; line-height: 32px"
        ></el-input>
        <el-button
          class="ml20"
          type="primary"
          @click="getAgencySubAccountList(1)"
        >
          查询
        </el-button>
      </div>
      <el-button class="ml20" type="primary" @click="dialogFormVisible = true">
        添加代理子账户
      </el-button>
      <el-dialog
        :title="ruleForm.id ? '编辑代理子账户' : '添加代理子账户'"
        v-model="dialogFormVisible"
        @closed="resetForm"
      >
        <template v-slot:default>
          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleFormRef"
            label-width="110px"
            label-position="left"
          >
            <el-form-item prop="userName" label="姓名">
              <el-input
                style="width: 280px"
                v-model="ruleForm.userName"
              ></el-input>
            </el-form-item>
            <el-form-item prop="phone" label="手机号" v-if="!ruleForm.id">
              <el-input
                style="width: 280px"
                v-model="ruleForm.phone"
              ></el-input>
            </el-form-item>
            <el-form-item prop="email" label="邮箱">
              <el-input
                style="width: 280px"
                v-model="ruleForm.email"
              ></el-input>
            </el-form-item>
            <el-form-item prop="password" label="密码" v-if="!ruleForm.id">
              <el-input
                style="width: 280px"
                v-model="ruleForm.password"
                placeholder="(不填自动生成)"
              ></el-input>
            </el-form-item>
            <el-form-item prop="isAdmin" label="管理员" v-if="!ruleForm.id">
              <el-select v-model="ruleForm.isAdmin" placeholder="是否管理员">
                <el-option label="否" value="0" />
                <el-option label="是" value="1" />
              </el-select>
            </el-form-item>
          </el-form>
        </template>
        <template v-slot:footer>
          <div class="dialog-footer">
            <el-button @click="resetForm">取 消</el-button>
            <el-button
              v-if="!ruleForm.id"
              type="primary"
              @click="addAgencySubAccount(ruleForm)"
            >
              确 定
            </el-button>
            <el-button
              v-else
              type="primary"
              @click="editAgencySubAccount(ruleForm)"
            >
              修改
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
    <div style="margin-top: 24px">
      <el-table :data="tableData" stripe style="width: 100%">
        <el-table-column
          type="index"
          label="序号"
          min-width="80"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="userName"
          label="姓名"
          min-width="120"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="phone"
          label="手机号"
          min-width="160"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          min-width="160"
          align="center"
        ></el-table-column>

        <el-table-column
          prop="deptName"
          label="部门"
          min-width="160"
          align="center"
        >
          <template v-slot="scope">
            {{ scope.row.deptName || "暂无部门" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="roleName"
          label="职位"
          min-width="160"
          align="center"
        >
          <template v-slot="scope">
            {{ scope.row.roleName || "暂无职位" }}
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="160" align="center">
          <template v-slot="scope">
            <el-button type="primary" size="small" @click="showEdit(scope.row)">
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="width: 100%; text-align: right; margin-top: 43px">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page="currentPage"
          :total="total"
          @current-change="pageChange"
        ></el-pagination>
      </div>
    </div>
  </div>
  <div class="container-title">货主信息</div>
  <div class="line-container-p24">
    <div style="display: flex; justify-content: space-between">
      <div style="display: flex">
        <el-input
          placeholder="公司名称/联系人/手机号"
          prefix-icon="el-icon-search"
          v-model="term2"
          clearable
          style="width: 330px"
        ></el-input>
        <el-button
          class="ml20"
          type="primary"
          @click="getCargoOwnerCompanyByAgencyCompany(1)"
        >
          查询
        </el-button>
      </div>
      <el-button class="ml20" type="primary" @click="dialogFormVisible2 = true">
        关联货主公司
      </el-button>
      <el-dialog
        title="关联货主公司"
        v-model="dialogFormVisible2"
        @closed="resetForm2"
      >
        <template v-slot:default>
          <el-form
            :model="ruleForm2"
            :rules="rules2"
            ref="form2"
            label-width="110px"
            label-position="left"
          >
            <el-form-item prop="cargoOwnerId" label="货主公司">
              <RemoteSearch
                api="getCargoOwnerCompanySelect"
                v-model="cargoOwnerCompanyStr"
                placeholder="公司名称/联系人/手机号"
                @selectItem="selectCargoOwner($event)"
                class="mb10"
              ></RemoteSearch>
            </el-form-item>
          </el-form>
        </template>
        <template v-slot:footer>
          <div class="dialog-footer">
            <el-button @click="resetForm2">取 消</el-button>
            <el-button type="primary" @click="relateCargoAgency(ruleForm2)">
              确认关联
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
    <div style="margin-top: 24px">
      <el-table :data="tableData2" stripe style="width: 100%">
        <el-table-column
          type="index"
          label="序号"
          min-width="80"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="cargoOwnerName"
          label="公司名称"
          min-width="120"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="contactName"
          label="联系人"
          min-width="120"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="contactPhone"
          label="联系人手机号"
          min-width="160"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="contactEmail"
          label="联系人邮箱"
          min-width="160"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="copId"
          label="操作"
          min-width="160"
          align="center"
        >
          <template v-slot="scope">
            <el-button
              type="danger"
              size="small"
              @click="unrelateCargoAgency(scope.row.cargoOwnerId)"
            >
              取消关联
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="width: 100%; text-align: right; margin-top: 43px">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page="currentPage2"
          :total="total2"
          @current-change="pageChange2"
        ></el-pagination>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, h, reactive, toRefs, onMounted } from "vue";
import {
  ElNotification,
  ElMessageBox,
  ElMessage,
  ElLoading,
} from "element-plus";
import store from "../../store";
import router from "../../router";
import { useRoute } from "vue-router";
import api from "../../apis/fetch";
import { subTimeStr } from "../../utils/utils";

const route = useRoute();
let dialogFormVisible = ref(false);
let ruleFormRef = ref(null);
let ruleForm = ref({
  userName: "",
  phone: "",
  email: "",
  password: "",
  isAdmin: "",
});
async function resetForm() {
  dialogFormVisible.value = false;
  ruleForm.value = {};
}
const rules = ref({
  userName: [
    { required: true, message: "请填写代理子账户名称", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "请填写手机号", trigger: "blur" },
    { min: 11, max: 11, message: "请正确填写手机号", trigger: "blur" },
  ],
  email: [{ required: true, message: "请填写邮箱", trigger: "blur" }],
});
async function addAgencySubAccount() {
  ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      let { userName, phone, email, password, isAdmin } = ruleForm.value;
      const loading = ElLoading.service({
        lock: true,
        text: "正在提交...",
        background: "rgba(0, 0, 0, 0.7)",
      });
      let res = await api.addAgencySubAccount({
        proxyId: route.query.id,
        userName,
        phone,
        email,
        password,
        isAdmin,
      });
      loading.close();
      if (res.data.status == 0) {
        ElNotification.success({
          title: "添加成功",
          duration: 0,
          message: `${userName}:${res.data.msg}`,
          type: "success",
        });
        resetForm();
        getAgencySubAccountList();
      } else {
        ElNotification.error({
          title: "失败",
          duration: 3000,
          message: res.data.msg,
        });
      }
    } else {
      return false;
    }
  });
}

function editAgencySubAccount() {
  ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      let { id: proxyLoginAccountId, userName, email } = ruleForm.value;
      const loading = ElLoading.service({
        lock: true,
        text: "正在提交...",
        background: "rgba(0, 0, 0, 0.7)",
      });
      let res = await api.editAgencySubAccount({
        proxyId: route.query.id,
        proxyLoginAccountId,
        userName,
        email,
      });
      loading.close();
      if (res.data.status == 0) {
        ElNotification.success({
          title: "修改成功",
          duration: 0,
          message: `${userName}:${res.data.msg}`,
          type: "success",
        });
        resetForm();
        getAgencySubAccountList();
      } else {
        ElNotification.error({
          title: "失败",
          duration: 3000,
          message: res.data.msg,
        });
      }
    } else {
      return false;
    }
  });
}
let currentPage = ref(1);
let term = ref("");
let tableData = ref([]);
let total = ref(0);
async function getAgencySubAccountList(page) {
  currentPage.value = page || currentPage.value;
  let res = await api.getAgencySubAccountList({
    currentPage: currentPage.value,
    size: 10,
    term: term.value,
    proxyId: route.query.id,
  });
  if (res.data.status == 0) {
    tableData.value = res.data.result;
    total.value = res.data.total;
  } else {
    tableData.value = [];
    total.value = 0;
  }
}

function pageChange(e) {
  currentPage.value = e;
  getAgencySubAccountList();
}
let proxyName = ref();
let shortName = ref();
let contactName = ref();
let contactPhone = ref();
let contactEmail = ref();
async function getAgencyCompanyDetail() {
  let res = await api.getAgencyCompanyDetail({
    proxyId: route.query.id,
  });
  if (res.data.status == 0) {
    proxyName.value = res.data.result.proxyName;
    shortName.value = res.data.result.shortName;
    contactName.value = res.data.result.contactName;
    contactPhone.value = res.data.result.contactPhone;
    contactEmail.value = res.data.result.contactEmail;
    expiredTime.value = res.data.result.expiredTime;
  } else {
    console.log(res);
  }
}

let tableData2 = ref([]);
let term2 = ref("");
let currentPage2 = ref(1);
let total2 = ref(0);
let dialogFormVisible2 = ref(false);
let form2 = ref(null);

async function getCargoOwnerCompanyByAgencyCompany(page) {
  currentPage2.value = page || currentPage2.value;
  let res = await api.getCargoOwnerCompanyByAgencyCompany({
    proxyId: route.query.id,
    currentPage: currentPage2.value,
    size: 10,
    term: term2.value,
  });
  if (res.data.status == 0) {
    tableData2.value = res.data.result;
    total2.value = res.data.total;
  } else {
    tableData2.value = [];
    total2.value = 0;
  }
}
let cargoOwnerCompanyStr = ref("");
const ruleForm2 = ref({
  cargoOwnerId: "",
});
const rules2 = ref({
  cargoOwnerId: [
    { required: true, message: "请选择货主公司", trigger: "blur" },
  ],
});

function selectCargoOwner(item) {
  ruleForm2.value.cargoOwnerId = item.key;
  console.log(ruleForm2.value);
}

function resetForm2() {
  dialogFormVisible2.value = false;
  cargoOwnerCompanyStr.value = "";
  form2.value.resetFields();
}

function pageChange2(e) {
  currenrPage2.value = e;
  getCargoOwnerCompanyByAgencyCompany();
}

async function relateCargoAgency() {
  form2.value.validate(async (valid) => {
    if (valid) {
      let { cargoOwnerId } = ruleForm2.value;

      let res = await api.relateCargoAgency({
        proxyId: route.query.id,
        cargoOwnerId,
      });
      console.log(res);
      if (res.data.status == 0) {
        ElNotification.success({
          title: "添加成功",
          duration: 2000,
          message: `${res.data.msg}`,
          type: "success",
        });
        resetForm2();
        getCargoOwnerCompanyByAgencyCompany();
      } else {
        ElNotification.error({
          title: "失败",
          duration: 3000,
          message: res.data.msg,
        });
      }
    } else {
      return false;
    }
  });
}

const unrelateCargoAgency = (cargoOwnerId) => {
  ElMessageBox.confirm(
    "取消关联后代理公司将无法继续为对应的货主公司创建航次，是否继续取消关联？",
    "警告",
    {
      confirmButtonText: "确认取消",
      cancelButtonText: "再想想",
      type: "warning",
    }
  )
    .then(async () => {
      console.log(cargoOwnerId);
      let res = await api.unrelateCargoAgency({
        cargoOwnerId,
        proxyId: route.query.id,
      });
      getCargoOwnerCompanyByAgencyCompany();
    })
    .catch(() => {
      // ElMessage({
      //   type: "info",
      //   message: "Delete canceled",
      // });
    });
};

let expiredTime = ref("");
let expiredTimeEditable = ref(false);
let expiredTimeCache = "";
function editExpiredTime() {
  expiredTimeCache = expiredTime.value;
  expiredTimeEditable.value = true;
}
async function submitExpiredTime() {
  let res = await api.updateAgencyExpiredTime({
    expiredTime: expiredTime.value,
    proxyId: route.query.id,
  });
  if (res.data.status == 0) {
    expiredTimeEditable.value = false;
  } else {
    console.log(res);
  }
}
function cancelExpiredTime() {
  expiredTime.value = expiredTimeCache;
  expiredTimeEditable.value = false;
}

function showEdit(row) {
  dialogFormVisible.value = true;
  ruleForm.value = {
    ...row,
  };
}

const isBasicInfoEdit = ref(false);
const nameCache = ref("");
const shortCache = ref("");
function editBasicInfo() {
  isBasicInfoEdit.value = true;
  nameCache.value = proxyName.value;
  shortCache.value = shortName.value;
}
async function submitBasicInfoEdit() {
  let { data } = await api.updateAgencyCompany({
    proxyId: route.query.id,
    companyName: proxyName.value,
    shortName: shortName.value,
  });
  if (data.status == 0) {
    ElNotification.success({
      title: "成功",
      duration: 2000,
      message: `${data.msg}`,
      type: "success",
    });
    getAgencyCompanyDetail();
    isBasicInfoEdit.value = false;
  } else {
    ElNotification.error({
      title: "失败",
      duration: 3000,
      message: data.msg,
    });
  }
}
function cancelBasicInfoEdit() {
  isBasicInfoEdit.value = false;
  proxyName.value = nameCache.value;
  shortName.value = shortCache.value;
}

onMounted(() => {
  getAgencyCompanyDetail();
  getCargoOwnerCompanyByAgencyCompany();
  getAgencySubAccountList();
});
</script>
<style scoped>
.go-back {
  font-size: 16px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: #333d43;
  line-height: 100%;
  cursor: pointer;
}

.normal-label {
  width: 100px;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #353a42;
  margin-right: 10px;
}

.show-input {
  width: 200px;
  height: 32px;
  background: #ffffff;
  border-radius: 2px;
  border: 1px solid #dee0e3;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #333333;
  line-height: 32px;
  padding-left: 12px;
  margin-right: 40px;
}

.radio-btns {
  height: 38px;
  width: 103px;
  border: 1px solid #1486f9;
  line-height: 38px;
  text-align: center;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #0094fe;
  cursor: pointer;
}

.left-radius {
  border-top-left-radius: 19px;
  border-bottom-left-radius: 19px;
}

.right-radius {
  border-top-right-radius: 19px;
  border-bottom-right-radius: 19px;
}
.currentbtn {
  background: #1486f9;
  color: #fff;
}

.seach-btn {
  display: inline-block;
  width: 60px;
  height: 38px;
  background: #0094fe;
  border-radius: 2px;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #ffffff;
  text-align: center;
  line-height: 38px;
  margin-left: 15px;
  cursor: pointer;
  box-sizing: border-box;
}

.seach-btn {
  display: inline-block;
  width: 60px;
  height: 38px;
  background: #0094fe;
  border-radius: 2px;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #ffffff;
  text-align: center;
  line-height: 38px;
  margin-left: 15px;
  cursor: pointer;
  box-sizing: border-box;
}

.cargo-owner-add {
  width: 120px;
  height: 36px;
  border-radius: 2px;
  border: 1px solid #0094fe;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #0094fe;
  line-height: 36px;
  text-align: center;
  cursor: pointer;
  margin-right: 20px;
}

:deep().el-dialog {
  width: 560px;
  padding: 20px 50px;
  border-radius: 6px;
}

:deep() .el-dialog__title {
  font-size: 18px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #0094fe;
}
</style>
