<template>
  <view class="changeUser">
    <view class="head">
      <view class="tab" :class="{active: tab.value === dataInfo.tabActiveValue}" v-for="tab in dataInfo.tabs" :key="tab.id" @click="clickTab(tab.value)">
        {{tab.name}}<text v-if="tab.num !== ''">({{tab.num}})</text>
      </view>
    </view>
    <scroll-view scroll-y class="body">
      <!-- 转派 -->
      <template v-if="dataInfo.tabActiveValue === 'redeploy'">
        <view class="form_item">
          <view class="title select"><text class="required newicon newicon-bitian"></text>工作组:</view>
          <uni-data-select class="value" v-model="dataInfo.groupId" :localdata="dataInfo.groupList" :clear="false" placeholder="请选择工作组" @change="changeGroup" :class="{formRed: isSubmit && !dataInfo.groupId}"></uni-data-select>
        </view>
        <view class="form_item">
          <view class="title radio"><text class="required newicon newicon-bitian"></text>是否转派到人:</view>
          <uni-data-checkbox class="value" v-model="dataInfo.isAssignUser" :localdata="dataInfo.isAssignUserList" @change="changeIsAssignUser" />
        </view>
        <view class="form_item" v-if="dataInfo.isAssignUser === 1">
          <view class="title select"><text class="required newicon newicon-bitian"></text>转派对象:</view>
          <uni-data-select class="value" v-model="dataInfo.userId" :localdata="dataInfo.userList" :clear="false" placeholder="请选择转派对象" :class="{formRed: isSubmit && dataInfo.groupId && dataInfo.isAssignUser == 1 && !dataInfo.userId}"></uni-data-select>
        </view>
      </template>
      
      <!-- 指派 -->
      <template v-if="dataInfo.tabActiveValue === 'assign'">
        <view class="form_item">
          <view class="title select"><text class="required newicon newicon-bitian"></text>院区:</view>
          <uni-data-select class="value" v-model="dataInfo.branchId" :localdata="dataInfo.branchList" :clear="false" placeholder="请选择院区" @change="changeBranch" :class="{formRed: isSubmit && !dataInfo.branchId}"></uni-data-select>
        </view>
        <view class="form_item">
          <view class="title select"><text class="required newicon newicon-bitian"></text>责任科室:</view>
          <uni-data-select class="value" v-model="dataInfo.dutyId" :localdata="dataInfo.dutyList" :clear="false" placeholder="请选择责任科室" @change="changeDuty" :class="{formRed: isSubmit && !dataInfo.dutyId}"></uni-data-select>
        </view>
        <view class="form_item">
          <view class="title select"><text class="required newicon newicon-bitian"></text>工作组:</view>
          <uni-data-select class="value" v-model="dataInfo.groupId" :localdata="dataInfo.groupList" :clear="false" placeholder="请选择工作组" @change="changeGroup" :class="{formRed: isSubmit && !dataInfo.groupId}"></uni-data-select>
        </view>
        <view class="form_item">
          <view class="title radio"><text class="required newicon newicon-bitian"></text>是否指派到人:</view>
          <uni-data-checkbox class="value" v-model="dataInfo.isAssignUser" :localdata="dataInfo.isAssignUserList" @change="changeIsAssignUser" />
        </view>
        <view class="form_item" v-if="dataInfo.isAssignUser === 1">
          <view class="title select"><text class="required newicon newicon-bitian"></text>指派对象:</view>
          <uni-data-select class="value" v-model="dataInfo.userId" :localdata="dataInfo.userList" :clear="false" placeholder="请选择指派对象" :class="{formRed: isSubmit && dataInfo.groupId && dataInfo.isAssignUser == 1 && !dataInfo.userId}"></uni-data-select>
        </view>
      </template>
      
      <!-- 退回 -->
      <template v-if="dataInfo.tabActiveValue === 'reassign'">
        <view class="form_item column">
          <view class="title"><text class="required newicon newicon-bitian"></text>退回原因:</view>
          <uni-easyinput class="value" type="textarea" v-model="dataInfo.reassignRemark" placeholder="请输入退回原因" :class="{formRed: isSubmit && !dataInfo.reassignRemark.trim()}" />
          <view class="tips">注:退回后,由调度台重新指派。</view>
        </view>
      </template>
    </scroll-view>
    <view class="foot_common_btns">
      <button @click="goBack" type="default" class="cancelButton btn">返回</button>
      <button @click="submit" type="default" class="primaryButton btn">提交</button>
    </view>
  </view>
</template>

<script setup>
  import { ref, reactive } from 'vue'
  import { onLoad } from '@dcloudio/uni-app'
  import { api_group, api_incidentDetail, api_user, api_incidentTask, api_branch, api_dutyDepartment } from "@/http/api.js"
  import { defaultColor } from '@/static/js/theme.js'
  import { useSetTitle } from '@/share/useSetTitle.js'
  import { useMakePhoneCall } from '@/share/useMakePhoneCall.js'
  import { useGoBack } from '@/share/useGoBack.js'
  import { useLoginUserStore } from '@/stores/loginUser'
  
  useSetTitle();
  const loginUserStore = useLoginUserStore();
  const { makePhoneCall }  = useMakePhoneCall();
  const { goBack }  = useGoBack();
  
  // 主题颜色
  const primaryColor = ref(defaultColor)
  
  // 数据
  const dataInfo = reactive({
    tabs: [
      // {id: 1, name: '转派', value: 'redeploy', num: ''},
      // {id: 2, name: '指派', value: 'assign', num: ''},
      // {id: 3, name: '升级', value: 'upgrade', num: ''},
      // {id: 4, name: '退回', value: 'reassign', num: ''},
    ],
    tabActiveValue: 0,//当前选择的tab
    incidentId: undefined,//事件ID
    incidentData: {},//事件对象
    groupList: [], //工作组列表
    groupId: undefined, //工作组ID
    userList: [], //用户列表
    userId: undefined, //用户ID
    branchList: [], //院区列表
    branchId: undefined, //院区ID
    dutyList: [], //责任科室列表
    dutyId: undefined, //责任科室ID
    isAssignUser: 1, //工作组是否转派到人
    isAssignUserList: [
      { text: '是', value: 1 },
      { text: '否', value: 0 },
    ], //工作组是否转派到人选项
    reassignRemark: '',//退回原因
  })
  
  // 是否提交
  const isSubmit = ref(false)
  
  // 重置
  function reset(){
    dataInfo.branchId = undefined;
    dataInfo.branchList = [];
    
    dataInfo.dutyId = undefined;
    dataInfo.dutyList = [];
    
    dataInfo.groupId = undefined;
    dataInfo.groupList = [];
    
    dataInfo.userId = undefined;
    dataInfo.userList = [];
    
    dataInfo.isAssignUser = 1;
    
    dataInfo.reassignRemark = '';
  }
  
  // 初始化表单
  function initForm(){
    if(dataInfo.tabActiveValue === 'redeploy'){
      getGroups();
    }else if(dataInfo.tabActiveValue === 'assign'){
      getBranchs();
    }
  }
  
  // 点击tab
  function clickTab(tabValue){
    if(dataInfo.tabActiveValue == tabValue){
      return;
    }
    dataInfo.tabActiveValue = tabValue;
    isSubmit.value = false;
    reset();
    initForm()
  }
  
  // 获取事件详情
  function getIncidentDetail(){
    uni.showLoading({
      title: "加载中",
      mask: true,
    });

    api_incidentDetail(dataInfo.incidentId).then(res => {
      uni.hideLoading();
      if(res.status == 200){
        dataInfo.incidentData = res.data || {};
        let transferFlag = false;//转派权限
        let assignFlag = false;//指派权限
        for (let i = 0; i < loginUserStore.loginUser.menu.length; i++) {
            if (loginUserStore.loginUser.menu[i].link == "shijianliebiao_assign") {
                assignFlag = true
            }
            if (loginUserStore.loginUser.menu[i].link == "shijianliebiao_transfer") {
                transferFlag = true
            }
        }
        
        // 转派
        if(dataInfo.incidentData.state.value == 'handler' && dataInfo.incidentData.handlingPersonnelUser && dataInfo.incidentData.handlingPersonnelUser.id == loginUserStore.loginUser.user.id && !assignFlag && transferFlag){
          dataInfo.tabs.splice(0, 0, {id: 1, name: '转派', value: 'redeploy', num: ''});
        }
        
        // 指派
        if((dataInfo.incidentData.state.value == 'pending' || dataInfo.incidentData.state.value == 'handler' || dataInfo.incidentData.state.value == 'reassign') && assignFlag){
          let index = dataInfo.tabs.findIndex(v => v.value === 'reassign');
          if(index < 0){
            dataInfo.tabs = [{id: 1, name: '指派', value: 'assign', num: ''}];
          }else{
            dataInfo.tabs.splice(index, 0, {id: 1, name: '指派', value: 'assign', num: ''});
          }
        }
        
        // 退回
        if(dataInfo.incidentData.state.value == 'pending' || dataInfo.incidentData.state.value == 'handler'){
          if(dataInfo.tabs.length){
            dataInfo.tabs.splice(dataInfo.tabs.length, 0, {id: 4, name: '退回', value: 'reassign', num: ''});
          }else{
            dataInfo.tabs = [{id: 4, name: '退回', value: 'reassign', num: ''}];
          }
        }
        
        dataInfo.tabActiveValue = dataInfo.tabs[0].value;
        
        initForm()
      }else{
        uni.showToast({
          icon: 'none',
          title: res.msg || '请求数据失败!'
        });
      }
    })
  }
  
  // 获取院区列表
  function getBranchs(){
    uni.showLoading({
      title: "加载中",
      mask: true,
    });
    let postData = {
      "idx": 0,
      "sum": 9999,
    };
    api_branch(postData).then(res => {
      uni.hideLoading();
      if(res.status == 200){
        res.list = res.list || [];
        dataInfo.branchList = res.list.map(v => ({
          text: v.hosName,
          value: v.id,
        }));
        
        if(loginUserStore.loginUser.user.duty){
          // 当前的所属责任科室
          dataInfo.branchId = loginUserStore.loginUser.user.duty.branch;
          changeBranch();
          
          dataInfo.dutyId = loginUserStore.loginUser.user.duty.id;
          changeDuty();
        }else if(loginUserStore.loginUser.user.branch){
          // 当前的所属院区
          dataInfo.branchId = loginUserStore.loginUser.user.branch.id;
        }
      }else{
        uni.showToast({
          icon: 'none',
          title: res.msg || '请求数据失败!'
        });
      }
    })
  }
  
  // 获取责任科室列表
  function getDutys(){
    uni.showLoading({
      title: "加载中",
      mask: true,
    });
    let postData = {
      "idx": 0,
      "sum": 9999,
      "dutyDepartment": {
        "branch": dataInfo.branchId,
      }
    };
    api_dutyDepartment(postData).then(res => {
      uni.hideLoading();
      if(res.status == 200){
        res.list = res.list || [];
        dataInfo.dutyList = res.list.map(v => ({
          text: v.dept,
          value: v.id,
        }));
      }else{
        uni.showToast({
          icon: 'none',
          title: res.msg || '请求数据失败!'
        });
      }
    })
  }
  
  // 获取工作组列表
  function getGroups(){
    uni.showLoading({
      title: "加载中",
      mask: true,
    });
    
    let duty = undefined;
    if(dataInfo.tabActiveValue === 'redeploy'){
      duty = dataInfo.incidentData.duty;
    }else if(dataInfo.tabActiveValue === 'assign'){
      duty = { id: dataInfo.dutyId };
    }
    
    let postData = {
      "idx": 0,
      "sum": 9999,
      "group": {
          "duty": duty,
          "selectType": "nouser"
      }
    };
    api_group(postData).then(res => {
      uni.hideLoading();
      if(res.status == 200){
        res.list = res.list || [];
        dataInfo.groupList = res.list.map(v => ({
          text: v.groupName,
          value: v.id,
        }));
      }else{
        uni.showToast({
          icon: 'none',
          title: res.msg || '请求数据失败!'
        });
      }
    })
  }
  
  // 获取用户列表
  function getUsers(){
    uni.showLoading({
      title: "加载中",
      mask: true,
    });
    let postData = {
      "idx": 0,
      "sum": 9999,
      "user": {
          "groupdata":{
            "id": dataInfo.groupId,
          },
          "roledata": {
              "rolecode": "first-line support"
          },
          "roledata2": {
              "rolecode": "second-line support"
          },
          "selectType": "1",
          "selectDetails": 1,
          "simple": true,
          "engineer": 1
      }
    };
    api_user(postData).then(res => {
      uni.hideLoading();
      if(res.status == 200){
        res.list = res.list || [];
        dataInfo.userList = res.list.map(v => ({
          text: v.name,
          value: v.id,
        }));
      }else{
        uni.showToast({
          icon: 'none',
          title: res.msg || '请求数据失败!'
        });
      }
    })
  }
  
  // 选择院区
  function changeBranch(){
    dataInfo.dutyId = undefined;
    dataInfo.dutyList = [];
    
    dataInfo.groupId = undefined;
    dataInfo.groupList = [];
    
    dataInfo.userId = undefined;
    dataInfo.userList = [];
    getDutys();
  }
  
  // 选择责任科室
  function changeDuty(){
    dataInfo.groupId = undefined;
    dataInfo.groupList = [];
    
    dataInfo.userId = undefined;
    dataInfo.userList = [];
    getGroups();
  }
  
  // 选择工作组
  function changeGroup(){
    dataInfo.userId = undefined;
    dataInfo.userList = [];
    getUsers();
  }
  
  // 选择是否转派到人
  function changeIsAssignUser(){
    dataInfo.userId = undefined;
  }
  
  // 提交
  function submit(){
    isSubmit.value = true;
    
    if(dataInfo.tabActiveValue === 'redeploy'){
      submitRedeploy();
    }else if(dataInfo.tabActiveValue === 'assign'){
      submitAssign();
    }else if(dataInfo.tabActiveValue === 'reassign'){
      submitReassign();
    }
  }
  
  // 转派提交
  function submitRedeploy(){
    if(!dataInfo.groupId){
      uni.showToast({
      	icon: 'none',
        title: '请选择工作组'
      });
      return;
    }
    
    if(dataInfo.isAssignUser == 1 && !dataInfo.userId){
      uni.showToast({
      	icon: 'none',
        title: '请选择指派对象'
      });
      return;
    }
    
    uni.showLoading({
      title: "加载中",
      mask: true,
    });
    
    let postData = {
      incident: dataInfo.incidentData,
    }
    
    if(dataInfo.userId){
      // 派人
      postData.incident.assignee = dataInfo.userId;
    } else {
      // 派组
      postData.incident.candidateGroups = dataInfo.groupId;
    }
    
    api_incidentTask(dataInfo.tabActiveValue, postData).then(res => {
      uni.hideLoading();
      if(res.state == 200){
        uni.showToast({
        	icon: 'none',
          title: '转派成功',
          mask: true,
        });
        setTimeout(() => {
          uni.reLaunch({
            url: '/pages/incidentList/incidentList',
          })
        }, 1500)
      }else{
        uni.showToast({
          icon: 'none',
          title: res.msg || '请求数据失败!'
        });
      }
    })
  }
  
  // 指派提交
  function submitAssign(){
    if(!dataInfo.branchId){
      uni.showToast({
      	icon: 'none',
        title: '请选择院区'
      });
      return;
    }
    
    if(!dataInfo.dutyId){
      uni.showToast({
      	icon: 'none',
        title: '请选择责任科室'
      });
      return;
    }
    
    if(!dataInfo.groupId){
      uni.showToast({
      	icon: 'none',
        title: '请选择工作组'
      });
      return;
    }
    
    if(dataInfo.isAssignUser == 1 && !dataInfo.userId){
      uni.showToast({
      	icon: 'none',
        title: '请选择指派对象'
      });
      return;
    }
    
    uni.showLoading({
      title: "加载中",
      mask: true,
    });
    
    let postData = {
      incident: dataInfo.incidentData,
    }
    
    if(dataInfo.userId){
      // 派人
      postData.incident.assignee = dataInfo.userId;
    } else {
      // 派组
      postData.incident.candidateGroups = dataInfo.groupId;
    }
    
    api_incidentTask(dataInfo.tabActiveValue, postData).then(res => {
      uni.hideLoading();
      if(res.state == 200){
        uni.showToast({
        	icon: 'none',
          title: '指派成功',
          mask: true,
        });
        setTimeout(() => {
          uni.reLaunch({
            url: '/pages/incidentList/incidentList',
          })
        }, 1500)
      }else{
        uni.showToast({
          icon: 'none',
          title: res.msg || '请求数据失败!'
        });
      }
    })
  }
  
  // 退回提交
  function submitReassign(){
    if(!dataInfo.reassignRemark.trim()){
      uni.showToast({
      	icon: 'none',
        title: '请填写退回原因'
      });
      return;
    }
    
    uni.showLoading({
      title: "加载中",
      mask: true,
    });
    
    let postData = {
      incident: dataInfo.incidentData,
    }
    
    postData.incident.reassignRemark = dataInfo.reassignRemark;
    
    api_incidentTask(dataInfo.tabActiveValue, postData).then(res => {
      uni.hideLoading();
      if(res.state == 200){
        uni.showToast({
        	icon: 'none',
          title: '退回成功',
          mask: true,
        });
        setTimeout(() => {
          uni.reLaunch({
            url: '/pages/incidentList/incidentList',
          })
        }, 1500)
      }else{
        uni.showToast({
          icon: 'none',
          title: res.msg || '请求数据失败!'
        });
      }
    })
  }
  
  onLoad((option) => {
    dataInfo.incidentId = option.incidentId;
    getIncidentDetail();
  })
</script>

<style lang="scss" scoped>
.changeUser{
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .head{
    height: 88rpx;
    display: flex;
    position: fixed;
    z-index: 99;
    width: 100%;
    background-color: #fff;
    font-size: 30rpx;
    .tab{
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;
      border-bottom: 4rpx solid transparent;
      &.active{
        color: $uni-primary;
        border-color: $uni-primary;
      }
    }
  }
  .body{
    margin-top: 88rpx;
    padding: 0 24rpx;
    box-sizing: border-box;
    flex: 1;
    min-height: 0;
    .form_item{
      display: flex;
      align-items: center;
      padding-top: 24rpx;
      min-height: 86rpx;
      &.column{
        height: auto;
        flex-direction: column;
        align-items: flex-start;
        .title{
          margin-right: 0;
        }
        .value{
          margin-top: 10rpx;
          padding-left: 20rpx;
          box-sizing: border-box;
        }
        .tips{
          padding: 24rpx;
          text-align: center;
          font-size: 22rpx;
          color: #909399;
          width: 100%;
          box-sizing: border-box;
        }
      }
      .title{
        font-size: 26rpx;
        display: flex;
        align-items: center;
        margin-right: 12rpx;
        &.select{
          width: calc(5em + 20rpx);
        }
      }
    }
  }
}
</style>