<template>
  <ion-page class="list-page company-list-page">
    <ion-header class="header-theme2">
      <ion-toolbar>
        <ion-buttons slot="start">
          <ion-icon :icon="arrowBackOutline" @click="back"></ion-icon>
        </ion-buttons>
        <ion-title>
          企业信息收集
        </ion-title>
      </ion-toolbar>
    </ion-header>
    <ion-content>
      <div class="stepFlex" v-if="!isEdit">
        <div v-for="(record,key) in stepList" :key="key" class="stepFlex-item">
          <div
              :class="[(record.val < formState.dataModel?.statusVal || formState.dataModel?.statusVal==stepList[stepList.length-1].val) ? 'greenCircle' :record.val == formState.dataModel?.statusVal ? 'now' : 'greyCircle']"></div>
          <div v-if="key !== stepList.length - 1"
               :class="[record.val < formState.dataModel?.statusVal ? 'greenline' : 'greyline']"></div>
          <div class="stepFlex-item-label">
            <p class="stepFlex-item-label-title">{{ record.title }}</p>
            <p class="stepFlex-item-label-desc">{{ record.desc }}</p>
          </div>
        </div>
      </div>
      <ion-list class="list-content">
        <ion-item>
          <ion-grid>
            <ion-row>
              <ion-col size="9">
                <span style="background-color: #3a7be0;display: inline-block;width: 3px;color: transparent;">|</span>
                &nbsp;岗位信息
              </ion-col>
              <ion-col style="text-align: right;">
                <ion-icon :icon="addCircleOutline" @click="onAdd()" style="font-size: 24px;"></ion-icon>
              </ion-col>
            </ion-row>
          </ion-grid>
        </ion-item>
        <ion-item v-for="(record,key) in postList" :key="key" detail>
          <ion-grid>
            <ion-row>
              <ion-col>
                <ion-label style="display: flex;justify-content: space-between;">
                  <ion-text>
                    {{ record.postName }}
                  </ion-text>
                </ion-label>
              </ion-col>
            </ion-row>
            <ion-row>
              <ion-col size="8">
                <ion-label>
                  <p>
                    <!--                    {{ record.jobVacancyTime }}至{{ calculateEndDate(record.jobVacancyTime, record.validDay) }}-->
                    {{ record.validTime }}至{{ calculateEndDate(record.validTime, record.validDay) }}
                  </p>
                </ion-label>
              </ion-col>
              <ion-col>
                <ion-label>
                  <p>
                    招聘数量：{{ record.recruitCount }}
                  </p>
                </ion-label>
              </ion-col>
            </ion-row>
          </ion-grid>
        </ion-item>
      </ion-list>
    </ion-content>
    <ion-footer>
      <ion-toolbar>
        <div slot="end">
          <ion-button shape="round" expand="block" @click="onSave">提交</ion-button>
        </div>
      </ion-toolbar>
    </ion-footer>
  </ion-page>
</template>
<script lang="ts">
import {computed, defineComponent, reactive, ref, watch} from "vue";
import {useRoute, useRouter} from "vue-router";
import {alertController, onIonViewDidEnter} from "@ionic/vue";
import {arrowBackOutline, addCircleOutline} from 'ionicons/icons';
import {saveCompanyPost, getCompanyPostList, getCompanyById} from '@/api/company/index'
import dayjs from "dayjs";

interface FormState {
  dataModel: any;
}

interface PostModel {
  postName?: string | null,
  recruitCount?: number | null,
  // jobVacancyTime?: string | null,
  validTime?: string | null,
  validDay: number | null
}

export default defineComponent({
  name: 'editPost',
  setup() {
    const router = useRouter();
    const route = useRoute();
    const isEdit = ref<any>();
    const postList = ref<PostModel[]>([]);
    const formState = reactive<FormState>({dataModel: {}});
    const stepList = ref([
      {
        title: '基础信息',
        desc: '企业基础信息',
        val: 1
      },
      {
        title: '岗位信息',
        desc: '企业岗位信息',
        val: 2
      }]);

    const onSave = () => {
      if (postList.value.length == 0) {
        presentAlert('没有要提交的岗位信息！');
        return null;
      }
      if (route.query.id) {
        getCompanyById(route.query.id + "").then(data => {
          formState.dataModel = data;
          formState.dataModel.postData = postList.value;
          saveCompanyPost(formState.dataModel).then(result => {
            if (result) {
              router.push({path: './list', query: {success: 1}});
            }
          })
        })
      } else {
        const jsonDataModel = localStorage.getItem("companyData");
        formState.dataModel = JSON.parse(jsonDataModel ?? "");
        formState.dataModel.postData = postList.value;
        saveCompanyPost(formState.dataModel).then(result => {
          if (result) {
            router.push({path: './list', query: {success: 1}});
          }
        })
      }
    }

    const loadData = () => {
      postList.value = [];
      getCompanyPostList({companyID: route.query.id, pageSize: 999, pageIndex: 1}).then(data => {
        postList.value = data.list;
        formatDataList();
        console.log(postList.value);
      });
    }

    const initData=()=>{
      if (route.query.id) {
        isEdit.value = true;
      }
      if (route.query.pageStatus == "3") {
        const jsonPostList = localStorage.getItem("postData");
        postList.value = JSON.parse(jsonPostList ?? "");
        formatDataList();
        console.log(postList);
      }
      if (route.query.id && route.query.pageStatus == "1") {
        loadData();
      } else if (!route.query.id && route.query.pageStatus == "1") {
        isEdit.value = false;
        formState.dataModel.statusVal = 2;
        postList.value = [];
      }
    }

    onIonViewDidEnter(() => {
      if(route.query.reload){
        initData();
      }
    });

    const formatDataList = () => {
      postList.value.map(item => {
        if (item.validTime)
          item.validTime = dayjs(item.validTime).format("YYYY-MM-DD");
      });
    }

    const onAdd = () => {
      const jsonPostList = JSON.stringify(postList.value);
      localStorage.removeItem("postData");
      localStorage.setItem("postData", jsonPostList);
      if (route.query.id) {
        router.push({path: './editPost', query: {addStatus: 1, id: route.query.id}});
      } else {
        router.push({path: './editPost', query: {addStatus: 1}});
      }
    }

    // 计算截止日期的方法
    const calculateEndDate = (validTime: any, validDay: any) => {
      debugger;
      const validDate = new Date(validTime);
      validDate.setDate(validDate.getDate() + Number.parseInt(validDay));
      // 获取年月日
      const year = validDate.getFullYear();
      const month = validDate.getMonth() + 1; // 注意月份是从0开始的，需要加1
      const day = validDate.getDate();
      return `${year}-${month}-${day}`;
    };

    const back = () => {
      if (isEdit.value) {
        router.push({path: './list'});
      } else {
        router.push({path: './edit', query: {pageStatus: 2}});
      }
    }

    const presentAlert = async (message: string) => {
      const alert = await alertController.create({
        header: '错误！',
        message: message,
        buttons: [
          '确定'
        ],
      });

      await alert.present();
    }

    watch(() => route.query, () => {
      if (route.query.date) {
        if (route.query.id && route.query.pageStatus == "1")
          loadData();
      }
    });

    return {
      formState,
      onAdd,
      postList,
      stepList,
      onSave,
      calculateEndDate,
      route,
      arrowBackOutline,
      addCircleOutline,
      presentAlert,
      router,
      isEdit,
      back
    }
  }
});
</script>

<style lang="less">
.next-btn {
  width: 100%;
  --border-radius: 0px;
  --background: #f2f2f5;
  margin: 20px 0 0 0;
  color: #363432;
  font-size: 14px;
}

.stepFlex {
  margin: 0;
  display: flex;
  width: 100%;

  .stepFlex-item {
    position: relative;
    flex: 1;
    text-align: center;
    margin-top: -10px;

    .stepFlex-item-label {
      padding-top: 60px;
      font-size: 14px;

      .stepFlex-item-label-title {
        margin-top: 30px;
      }

      .stepFlex-item-label-desc {
        margin-top: 5px;
        color: #b9b9bd;
      }
    }
  }

  .greenCircle {
    top: calc(50% - 15px);
    left: calc(50% - 4px);
    position: absolute;
    z-index: 2;
    width: 10px;
    height: 10px;
    border-radius: 50%;
    background-color: #31A2FE;
  }

  .now {
    top: calc(50% - 18px);
    left: calc(50% - 8px);
    position: absolute;
    z-index: 3;
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: #31A2FE;
    border: 4px solid #c5e8f9;
  }

  .greyCircle {
    top: calc(50% - 15px);
    left: calc(50% - 4px);
    position: absolute;
    z-index: 2;
    width: 10px;
    height: 10px;
    border-radius: 50%;
    background-color: #ccc;
  }

  .greenline {
    width: 100%;
    top: calc(50% - 11px);
    left: calc(50% - 2px);
    height: 2px;
    background-color: #31A2FE;
    position: absolute;
  }

  .greyline {
    height: 0;
    border: 1px dashed #ccc;
    width: 100%;
    top: calc(50% - 11px);
    left: calc(50% - 2px);
    position: absolute;
  }


  .company-list-page {
    .list-content {
      margin: 0px 15px !important;
      background-color: white !important;
      border-radius: 0 !important;

      ion-item {
        margin-top: 10px;
        font-size: 14px;
        border: 1px solid rgb(242, 242, 245);

        p {
          font-size: 12px;
        }
      }
    }
  }

}

</style>