<template>
  <HcCard actionUi="text-center">
    <template #header>
        <div class="hc-expense-total-title">出差天数:0.5</div>
    </template>
      <div class="hac-card-project-box">
          <div class="left-box">
              <el-scrollbar>
                  <el-form ref="formRef" :model="formModel" :rules="formRules" label-width="auto" size="large" :disabled="dataType === 'view'">
                      <div class="project-form-top">
                       
                              <el-form-item label="出差事由：" prop="tripDesc">
                                  <el-input v-model="formModel.tripDesc"/>
                              </el-form-item>
                              <HcCardItem :title="'行程'+ Number(index+1) " class="mt-2 hc-card-item-box" v-for="(item,index) in formModel.journeyList" ui="hac-bg-grey">
                        
                                    <el-form :ref="(el) => setFormItemRefs(el, index)" :model="item" :rules="formItemRules" label-position="left" size="large">
                                            <el-form-item label="交通工具" prop="trafficType">
                                                <el-select v-model="item.trafficType" block clearable placeholder="请选择">
                                                    <el-option v-for="item in trafficTypeData" :label="item.dictName" :value="item.dictValue"/>
                                                </el-select>
                                            </el-form-item>
                                            <el-form-item label="单程往返" prop="isSingletonType">
                                                <el-select v-model="item.isSingletonType" block clearable placeholder="请选择">
                                                    <el-option v-for="item in wayType" :label="item.name" :value="item.key"/>
                                                </el-select>
                                            </el-form-item>
                                            <el-form-item label="出发城市" prop="startCity">
                                                <el-select v-model="item.startCity" block clearable placeholder="请选择出发城市">
                                                    <el-option v-for="item in cityType" :label="item.name" :value="item.key"/>
                                                </el-select>
                                            </el-form-item>
                                            <el-form-item label="目的城市" prop="endCity">
                                                <el-select v-model="item.endCity" block clearable placeholder="请选择目的城市">
                                                    <el-option v-for="item in cityType" :label="item.name" :value="item.key"/>
                                                </el-select>
                                            </el-form-item>
                                            <el-form-item label="开始时间">
                                                <el-date-picker
                                                    v-model="item.startDate"
                                                    type="date"
                                                    placeholder="请选择开始时间"
                                                    style="width: 100%;"
                                                    format="YYYY-MM-DD"
                                                    value-format="YYYY-MM-DD"  
                                                />
                                            </el-form-item>
                                            <el-form-item label="结束时间">
                                                <el-date-picker
                                                    v-model="item.endDate"
                                                    type="date"
                                                    placeholder="请选择结束时间"
                                                    style="width: 100%;"
                                                    format="YYYY-MM-DD" 
                                                    value-format="YYYY-MM-DD"  
                                                />
                                            </el-form-item>
                                            <el-form-item label="时长" prop="duration">
                                                <el-input v-model="item.duration" disabled :getdata="getDiffDaydata(item)"/>
                                            </el-form-item>
                               
                            </el-form>
                                  <span class="tip ml-8">时长将自动计入考勤统计</span>
                                  <!-- <template #extra>
                                        <el-button type="primary" size="small"  @click="addJourney(item,index)">
                                            <HcIcon name="add"/>
                                            <span>增加行程</span>
                                        </el-button>
                                        <el-button type="warning" size="small" @click="delJourney(item,index)" class="ml-2">
                                            <HcIcon name="delete-bin-2"/>
                                            <span>删除行程</span>
                                        </el-button>
                                    </template> -->
                                    <template #extra>
                                        <el-button type="danger" size="small" @click="delJourney(index)" v-if="index > 0">
                                            <HcIcon name="delete-bin"/>
                                            <span>删除行程</span>
                                        </el-button>
                                    </template>
                              </HcCardItem>
                              <div  class="mt-16" style="margin-bottom: 40px;">
                                <el-divider content-position="right" border-style="dashed">
                                      <el-button type="primary" hc-btn   @click="addJourney(item,index)">
                                          <HcIcon name="add"/>
                                          <span>添加行程</span>
                                      </el-button>
                               </el-divider>
                              </div>
                            
                              <el-form-item label="出差天数：" prop="durationAll" class="mt-4">
                                  <el-input v-model="formModel.durationAll" disabled/>
                              </el-form-item>
                              <el-form-item label="出差备注：" prop="remarks" >
                                  <el-input v-model="formModel.remarks" type="textarea"/>
                              </el-form-item>
                              <el-form-item label="同行人" prop="fellowTravelerUserIds">
                                <el-select
                                        v-model="formModel.fellowTravelerUserIds"
                                        block clearable
                                        placeholder="请选择"
                                        style="width: 100%"
                                        >
                                        <el-option
                                            v-for="item in partneroptions"
                                            :key="item.key"
                                            :label="item.name"
                                            :value="item.key"
                                        />
                                        </el-select>
                              </el-form-item>
                              <el-form-item label="所属项目" prop="projectId" placeholder="请选择同行人">
                                        <el-select v-model="formModel.projectId" block clearable placeholder="请选择">
                                          <el-option v-for="item in projectType" :label="item.projectName" :value="item.projectId"/>
                                      </el-select>
                              </el-form-item>
                              <el-form-item label="关联预算计划" prop="key">
                                <el-button type="primary" size="small"  @click="budgetModalShow">
                                            <HcIcon name="add"/>
                                            <span>关联预算计划</span>
                                </el-button>
                              </el-form-item>
                             
                          
                       
                      </div>
              
                  </el-form>
              </el-scrollbar>
          </div>
          <div class="right-box">
            <div class="record-flow-box">
                <div class="title">流程</div>
                <div class="content">
                    <el-scrollbar>
                        <el-timeline>
                            <el-timeline-item v-for="(item, index) in timeLineData" :key="index">
                                <div class="timeline-title">{{item.title}}</div>
                                <div class="timeline-section">{{item.section}}</div>
                            </el-timeline-item>
                        </el-timeline>
                    </el-scrollbar>
                </div>
                <div class="action">
                    <el-button type="warning" hc-btn @click="tempDraftData" :loading="tempLoading">
                        <HcIcon name="draft"/>
                        <span>暂存草稿</span>
                    </el-button>
                    <el-button type="primary" hc-btn @click="saveClick" :loading="saveLoading">
                        <HcIcon name="check-double"/>
                        <span>提交出差申请</span>
                    </el-button>
                </div>
            </div>
          </div>
      </div>
      <!--关联预算计划-->
      <HcDialog bgColor="#ffffff" isToBody isTable
                  title="关联预算计划" widths="80%" saveText="保存"
                  :show="budgetModal"
                  @close="budgetCloseClick"
                  @save="budgetSaveClick"
        >
            <HcTable :column="tableBudgetColumn" :datas="tableBudgetData">
                <template #action="{row,index}">
                    <el-button size="small" type="danger" @click="row.relevance = false" v-if="row.relevance">取消关联</el-button>
                    <el-button size="small" type="primary" @click="row.relevance = true" v-else>关联</el-button>
                </template>
            </HcTable>
      </HcDialog>
  </HcCard>
</template>

<script setup>
import {ref, onActivated,watch} from "vue";
import {useRoute, useRouter} from 'vue-router'
import {getProjectList, getDictInfo} from "~api/other";
import {arrIndex, deepClone, formValidate, getArrValue} from "js-fast-way";
import businessApi from '~api/attendance/business-trip.js';
import {getDiffDay} from "~uti/tools";

const router = useRouter()
const useRoutes = useRoute()

//初始变量
const dataType = ref(useRoutes?.query?.type ?? 'view')
const dataId = ref(useRoutes?.query?.id ?? '')

//缓存页面被激活时
onActivated(() => {
  dataType.value = useRoutes?.query?.type ?? 'view'
  dataId.value = useRoutes?.query?.id ?? ''
  getTrafficType()
  getProjectData()
  getDetailsData()
})
const getDetailsData = async () => {
    if (dataType.value === 'view') {
        //预览详情
        let newDetails = {}, newDetails1 = {}
        const {error, code, data, msg} = await businessApi.detail({
            id: dataId.value
        })
        //判断状态
        if (!error && code === 200) {
            const res = getObjValue(data)
            //基础数据
            Object.keys(detailsObj).forEach(key => {
                newDetails[key] = res[key]
            })
            //明细数据
            Object.keys(detailsObj1).forEach(key => {
                newDetails1[key] = res[key]
            })
            newDetails1.id = res?.id
         
            newDetails.details = [newDetails1]
        } else {
            newDetails = detailsObj
            newDetails.details = [detailsObj1]
      
            window.$message?.error(msg)
        }
        detailsData.value = newDetails
    } else if (dataType.value === 'draft') {
        //草稿详情
        const {error, code, data} = await businessApi.draftDetail({
            eMDraftIds: dataId.value
        })
        //判断状态
        const res = getArrValue(data)
        if (!error && code === 200 && res.length > 0) {
            let newDetails = {}, newDetailsArr = []
            res.forEach((item, index) => {
                //基础数据
                if (index === 0) {
                    Object.keys(detailsObj).forEach(key => {
                        newDetails[key] = item[key]
                    })
                }
                //明细数据
                let newDetails1 = {}
                Object.keys(detailsObj1).forEach(key => {
                    newDetails1[key] = item[key]
                })
                newDetails1.id = item?.id
                newDetailsArr.push(newDetails1)
              
            })
            newDetails.journeyList = newDetailsArr
            console.log(formModel.value,'formModel.value');
            formModel.value = newDetails
        } else {
          
            formModel.value = {
                ...detailsObj,
                details: [detailsObj1]
            }
        }
    } else {

        formModel.value = {
            ...detailsObj,
            details: [detailsObj1]
        }
    }
}
//获取间隔天数
const getDiffDaydata=(item)=>{
   let time= getDiffDay(item.startDate,item.endDate)
   item.duration=time
}
//行程表单
const formItemRules = {
    isSingletonType: {
      required: true,
      trigger: 'blur',
      message: "请选择单程往返"
  },
  trafficType: {
      required: true,
      trigger: 'blur',
      message: "请选择交通工具"
  },
  startCity: {
      required: true,
      trigger: 'blur',
      message: "请选择出发城市"
  },
  endCity: {
      required: true,
      trigger: 'blur',
      message: "请选择目的城市"
  },
  startDate: {
      required: true,
      trigger: 'blur',
      message: "请选择开始时间"
  },
  endDate: {
      required: true,
      trigger: 'blur',
      message: "请选择结束时间"
  },
  duration: {
      required: true,
      trigger: 'blur',
      message: "请输入时长"
  },
  durationAll:{
    required: true,
      trigger: 'blur',
      message: "请输入天数"
  },
}
const formRefs = ref([])
const setFormItemRefs = (el, index) => {
    if (el) {
        let indexs = arrIndex(formRefs.value, 'index', index)
        if (indexs !== -1) {
            formRefs.value[index].ref = el
        } else {
            formRefs.value.push({index: index, ref: el});
        }
    }
}

//获取表单的ref
const getFormRef = async (index) => {
    const indexs = arrIndex(formRefs.value, 'index', index)
    return formRefs.value[indexs].ref
}

//增加行程addJourney
const addJourney=(item,index)=>{
   formModel.value?.journeyList.push({})
}
const delJourney=(item,index)=>{
    console.log(index,'index');
    formModel?.value.journeyList.splice(index, 1)
}
//单程往返
const wayType = ref([
  {name: '单程', key: 1},
  {name: '往返', key: 2},
 
])
//交通工具
const trafficTypeData=ref([

])
//交通类型字典
const getTrafficType= async () => {
    const {error, code, data} = await getDictInfo('traffic_type')
    //判断状态
    if (!error && code === 200) {
        trafficTypeData.value = getArrValue(data)
    } else {
        trafficTypeData.value = []
    }
}
//出发城市cityType
const cityType=ref([
  {name: '北京', key: '1'},
  {name: '上海', key: '2'},
  {name: '深圳', key: '3'},
  {name: '成都', key: '4'},
])
//项目类型
const projectType = ref([

])

//获取项目数据

const getProjectData = async () => {
    const {error, code, data} = await getProjectList()
    //判断状态
    if (!error && code === 200) {
        projectType.value = getArrValue(data)
    } else {
        projectType.value = []
    }
}
//同行人
const partneroptions = ref([
  {name: '小黄', key: '1'},
  {name: '香兰', key: '2'},
  {name: '小黑', key: '3'},
])
//合同类型
const contractType = ref([
  {name: '咨询服务+软件', key: '1'},
  {name: '软件', key: '2'},
  {name: '咨询服务', key: '3'},
  {name: '后期服务+软件', key: '4'},
  {name: '数字化扫描+软件', key: '5'},
])



//顶部表单数据
const formRef = ref(null)
const formModel = ref({
    journeyList:[{}]
})
//深度监听
watch(() => [
    formModel.value.journeyList
], ([datas]) => {
   let timeall=0
   formModel.value.journeyList.forEach((ele)=>{
    timeall=ele.duration+timeall
   })
   formModel.value.durationAll=timeall//计算总时长
}, {deep: true})
const formRules = {
    tripDesc: {
      required: true,
      trigger: 'blur',
      message: "请输入项出差事由"
  },
 
  projectId: {
      required: true,
      trigger: 'blur',
      message: "请选择项目"
  },


}


//日期时间被选择
const betweenTime = ref(null)
const betweenTimeUpdate = ({arr, query}) => {
  betweenTime.value = arr
  //formModel.value.betweenTime = query
}


//时间线数据
const timeLineData = ref([
    {title: '审批人', section: '部门负责人'},
    {title: '人事审批', section: '人事'},

    {title: '抄送人', section: '总经理'},
  
])

//返回
const goBackClick = () => {
  router.back()
}

//提交保存
const doubleClick = () => {

}

//关联预算计划
const budgetModal = ref(false)
const budgetModalShow = () => {
    budgetModal.value = true
}
const budgetCloseClick = () => {
    budgetModal.value = false
}
const budgetSaveClick = () => {

}

//关联预算计划表格
const tableBudgetColumn = [
    {key: 'key1', name: '任务所属项目'},
    {key: 'key2', name: '状态',  width: '120', align: 'center'},
    {key: 'key3', name: '任务描述'},
    {key: 'key4', name: '完成指标', width: '120', align: 'center'},
    {key: 'action', name: '操作', width: '100', align: 'center'},
]
const tableBudgetData = ref([
    {id: 1, key1: 'xxxx'},
    {id: 2, key1: 'xxxx'},
    {id: 3, key1: 'xxxx'},
    {id: 4, key1: 'xxxx'},
])
//行程
const detailsObj1 = {
    trafficType: '',             // 交通工具
    isSingletonType: '',       // 单程往返
    startCity: '',    // 出发城市
    endCity: '',        //目的城市
    startDate: null,           // 开始时间
    endDate: null,           // 结束时间
    duration: null,           // 时长
    //details: [detailsObj1],
}
//基础详情
const detailsObj = {
  
    tripDesc: '',             // 出差事由
    durationAll: 0,       // 出差天数
    fellowTravelerUserIds: '',    // 同行人
    remarks: '',        //出差备注
    projectId: '',     // 所属项目
    submitStatus: null,           // 审提交状态 1=暂存 2=提交审批
    journeyList: [detailsObj1],
}

//处理表单数据
const getFormData = (submitStatus = 1) => {
    const res = deepClone(formModel.value)
  
    const ccUserList = [{userId: ''}]           //抄送人列表
    const personnelUser = {userId: ''}  //人事
    const financeUser = {userId: ''}            //财务人员
    const responsibleUser = {userId: ''}        //部门负责人
    //----处理数据----
    let newFormData = [], newDetails = {}
    //基础数据
    Object.keys(detailsObj).forEach(key => {
        newDetails[key] = res[key]
    })
    //组装为数组集合的表单数据
    const list = res?.journeyList
    list.forEach(item => {
        newFormData.push({
            ...newDetails,
            ...item,
            ccUserList,
            personnelUser,
            financeUser,
            responsibleUser,
            submitStatus //提交状态 1=暂存 2=提交审批
        })
    })
    return newFormData
}
const saveLoading=ref(false)
const saveClick=async()=>{
    const res = await formValidate(formRef.value)
    if (!res) return false;
    //处理明细表单效验
    saveLoading.value = true
    const form = getFormData(2)
    for (let i = 0; i < form.length; i++) {
        const refs = await getFormRef(i)
        const res = await formValidate(refs)
        if (!res) {
            saveLoading.value = false
            return
        }else{
            const {error, code, msg} = await businessApi.submit(form)
            //判断状态
            tempLoading.value = false
            if (!error && code === 200) {
                window.$message?.success('保存成功')
            } else {
                window.$message?.error(msg)
             }
        }
    }
    //发起请求
}
//暂存数据
const tempLoading = ref(false)
const tempDraftData = async () => {
    tempLoading.value = true
    const form = getFormData(1)
    const {error, code, msg} = await businessApi.submit(form)
    //判断状态
    tempLoading.value = false
    if (!error && code === 200) {
        window.$message?.success('暂存成功')
    } else {
        window.$message?.error(msg)
    }
}
</script>

<style lang="scss" scoped>
.hac-card-project-box {
  position: relative;
  height: 100%;
  display: flex;
  .left-box, .right-box {
    //   flex: 1;
      position: relative;
      height: 100%;
  }
  .left-box {
    flex: 2;
      .project-form-top {
          margin-bottom: 24px;
          padding-right: 24px;
      }
      .project-form-bottom {
          padding-top: 24px;
          padding-right: 24px;
          border-top: 1px solid #e9e9e9;
      }
  }
  .right-box {
    // flex: 1;
      padding-left: 24px;
    //   border-left: 1px solid #e9e9e9;
     
      .record-flow-box {
        position: relative;
        height: 100%;
        width: 380px;
        padding-left: 24px;
        border-left: 1px solid #e9e9e9;
        .title {
            position: relative;
            font-size: 20px;
            color: #101010;
            font-weight: bold;
            margin-bottom: 20px;
        }
        .content {
            position: relative;
            height: calc(100% - 60px - 43px);
            .timeline-title {
                font-size: 20px;
                color: #101010;
            }
            .timeline-section {
                margin-top: 10px;
                color: #1784FC;
                font-size: 16px;
            }
        }
        .action {
            position: relative;
            padding: 10px 0;
            display: flex;
            justify-content: space-around;
        }
    }
  }
}
.tip{
    color: gray;
  
    font-size: 14px;
}
.right-box-title{
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 40px;
}
.hc-expense-total-title {
    color: #101010;
    font-size: 20px;
}
.hac-card-project-box .left-box .hc-card-item-box.hac-bg-grey {
    background: #f7f7f7;
}
</style>

<style lang="scss">

</style>
