<template>
  <view class="buildIncident">
		<!-- 原来的scroll-view -->
    <view class="body view-body"> 
      <view class="form_item">
        <view class="title select"><text class="required newicon newicon-bitian"></text>院区：</view>
        <!-- <uni-data-select class="value" v-model="incidentData.branch" :localdata="dataInfo.branchList" :clear="false" placeholder="请选择院区" :class="{formRed: isSubmit && !incidentData.branch}" @change="changeBranch"></uni-data-select> -->
<!-- 				<uni-data-picker class="value" placeholder="请选择院区" 
					:localdata="dataInfo.branchList" v-model="incidentData.branch" :clear-icon="false"
					:class="{formRed: isSubmit && !incidentData.branch}" @change="changeBranch">
				</uni-data-picker> -->
				<view class="value size-14">
					{{loginUserStore.loginUser.user.currentHospital.parent?
					loginUserStore.loginUser.user.currentHospital.parent.hosName:
					loginUserStore.loginUser.user.currentHospital.hosName}}
				</view>
			</view>
      <view class="form_item">
        <view class="title"><text class="required newicon newicon-bitian"></text>报修科室：</view>
        <view class="value category" @click="selectDepartment">
          <text class="categoryName ellipsis-multiline">{{incidentData.department ? incidentData.department.dept : ''}}</text>
          <text class="newicon newicon-weibiaoti2010104"></text>
        </view>
      </view>
      <view class="form_item">
        <view class="title"><text class="required newicon newicon-bitian transparent"></text>报修人：</view>
        <view class="value category" @click="selectRequester">
          <text class="categoryName ellipsis-multiline">{{incidentData.requester ? incidentData.requester.name : ''}}</text>
          <text class="newicon newicon-weibiaoti2010104"></text>
        </view>
      </view>
      <view class="form_item">
        <view class="title select"><text class="required newicon newicon-bitian transparent"></text>联系人：</view>
        <uni-easyinput class="value" v-model="incidentData.contacts" placeholder="请输入联系人" />
      </view>
      <view class="form_item">
        <view class="title select"><text class="required newicon newicon-bitian"></text>联系电话：</view>
        <uni-easyinput class="value" v-model="incidentData.contactsInformation" placeholder="请输入联系电话" :class="{formRed: isSubmit && !incidentData.contactsInformation.trim()}" />
      </view>
      <view class="form_item">
        <view class="title"><text class="required newicon newicon-bitian transparent"></text>楼栋楼层：</view>
        <view class="value category" @click="selectAreaPlace">
          <text class="categoryName ellipsis-multiline" v-if="incidentData.place">{{incidentData.place ? incidentData.place.building.buildingName:''}} {{ incidentData.place&&incidentData.place.floor?incidentData.place.floor.floorName : incidentData.place.floorName}}</text>
          <text class="newicon newicon-weibiaoti2010104"></text>
        </view>
      </view>
      <view class="form_item">
        <view class="title select"><text class="required newicon newicon-bitian transparent"></text>详细地址：</view>
        <uni-easyinput class="value" v-model="incidentData.houseNumber" placeholder="请输入详细地址" />
      </view>
      <view class="form_item">
        <view class="title"><text class="required newicon newicon-bitian"></text>故障现象：</view>
        <view class="value category" @click="selectCategory">
          <text class="categoryName ellipsis-multiline">{{incidentData.category ? incidentData.category.mutiCategory : ''}}</text>
          <text class="newicon newicon-weibiaoti2010104"></text>
        </view>
      </view>
      <view class="form_item">
        <view class="title select"><text class="required newicon newicon-bitian"></text>故障来源：</view>
        <!-- <uni-data-select readonly class="value" v-model="incidentData.source" :localdata="dataInfo.sourceList" placeholder="请选择故障来源" :class="{formRed: isSubmit && !incidentData.source}"></uni-data-select> -->
				<uni-data-picker class="value" placeholder="请选择故障来源" 
					:localdata="dataInfo.sourceList" v-model="incidentData.source" 
					:clear-icon="false" :class="{formRed: isSubmit && !incidentData.source}">
				</uni-data-picker>
			</view>
      <view class="form_item">
        <view class="title select"><text class="required newicon newicon-bitian"></text>优先级：</view>
        <!-- <uni-data-select placement="top" readonly class="value" v-model="incidentData.priority" :localdata="dataInfo.priorityList" placeholder="请选择优先级" :class="{formRed: isSubmit && !incidentData.priority}"></uni-data-select> -->
				<uni-data-picker placement="top" class="value" placeholder="请选择优先级"
					:localdata="dataInfo.priorityList" v-model="incidentData.priority" 
					:clear-icon="false" :class="{formRed: isSubmit && !incidentData.priority}">
				</uni-data-picker>
			</view>
      <view class="form_item column">
        <view class="title select"><text class="required newicon newicon-bitian"></text>故障描述：</view>
        <uni-easyinput class="value" type="textarea" v-model="incidentData.description" placeholder="请输入故障描述" :class="{formRed: isSubmit && !incidentData.description.trim()}" />
      </view>
      <view class="form_item_column">
        <view class="form_item">
          <view class="title"><text class="required newicon newicon-bitian transparent"></text>报修图片：</view>
          <view class="value">
            <uni-file-picker ref="handlerImgRef" v-model="incidentData.repairImgList" limit="3" @success="handlerImgSuccess" @fail="handlerImgFail" @select="handlerImgSelect" @delete="handlerImgDelete"></uni-file-picker>
          </view>
        </view>
        <view class="form_item">
          <view class="title transparent"><text class="required newicon newicon-bitian transparent"></text>报修图片：</view>
          <view class="value">
            <text class="imgTips ellipsis">(支持JPG/PNG格式图片，单张大小10M以内)</text>
          </view>
        </view>
      </view>

    </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_branch, api_getDictionary, getFetchDataList, api_incidentTask } from "@/http/api.js"
  import { defaultColor } from '@/static/js/theme.js'
  import { useSetTitle } from '@/share/useSetTitle.js'
  import { useGoBack } from '@/share/useGoBack.js'
  import { useLoginUserStore } from '@/stores/loginUser'
  import { useIncidentBuildStore } from '@/stores/incidentBuild'
  import { useHandlerStore } from '@/stores/handler'
  import { useUploadFile } from '@/share/useUploadFile.js'

  useSetTitle();
  const loginUserStore = useLoginUserStore();
  const incidentBuildStore = useIncidentBuildStore();
  const handlerStore = useHandlerStore();
  const { uploadFile }  = useUploadFile();
  const { goBack }  = useGoBack();

  // 主题颜色
  const primaryColor = ref(defaultColor)
	
  // 工单对象
  const incidentData = reactive({
    "deleteFlag": 0,
    "duty": undefined,
    "department": undefined,
    "contactsInformation": '',
    "contacts": '',
    "branch": undefined,
    "area": undefined,
    "place": undefined,
    "houseNumber": '',
    "category": undefined,
    "priority": undefined,
    "source": undefined,
    "title": '',
    "description": '',
    "repairType": undefined,
    "requester":undefined,
    "acceptUser": loginUserStore.loginUser.user,
    repairImgList: [],//报修图片列表
  })

  // 报修图片
  const handlerImgRef = ref(null)

  // 数据
  const dataInfo = reactive({
    branchList: [], //院区列表
    sourceList: [], //故障来源列表
    priorityList: [], //优先级列表
  })

  // 是否提交
  const isSubmit = ref(false)

  // 上传报修图片成功
  function handlerImgSuccess(e){
    incidentData.repairImgList.forEach(v => {
      v.url = v.path;
    })
    console.log(incidentData.repairImgList);
  }

  // 上传报修图片失败
  function handlerImgFail(e){
    incidentData.repairImgList.forEach(v => {
      v.url = v.path;
    })
    console.log(incidentData.repairImgList);
  }

  // 选择上传图片
  function handlerImgSelect(e){
    incidentData.repairImgList = incidentData.repairImgList.concat(e.tempFiles);
    console.log(incidentData.repairImgList);
  }

  // 删除上传图片
  function handlerImgDelete(e){
    incidentData.repairImgList = incidentData.repairImgList.filter(v => e.tempFile.uuid != v.uuid);
    console.log(incidentData.repairImgList);
  }

  // 选择故障现象
  function selectCategory(){
    incidentBuildStore.setIncidentBuildData(incidentData, 'buildIncident');
    uni.navigateTo({
      url: `/pages/categoryOne/categoryOne`
    })
  }

  // 选择楼栋楼层
  function selectAreaPlace(){
    incidentBuildStore.setIncidentBuildData(incidentData, 'buildIncident', 'area');
    uni.navigateTo({
      url: `/pages/searchArea/searchArea`
    })
  }

  // 跳转到搜索报修科室
  function selectDepartment(){
    incidentBuildStore.setIncidentBuildData(incidentData, 'buildIncident', 'department');
    uni.navigateTo({
      url: `/pages/searchDept/searchDept`
    })
  }
  
  // 跳转到搜索报修人
  function selectRequester(){
    incidentBuildStore.setIncidentBuildData(incidentData, 'buildIncident', 'requester');
    uni.navigateTo({
      url: `/pages/searchUser/searchUser`
    })
  }

  // 获取院区列表
  function getBranchs(){
		if(loginUserStore.loginUser.user.currentHospital.parent){
			incidentData.branch = loginUserStore.loginUser.user.currentHospital.parent.id
		}else{
			incidentData.branch = loginUserStore.loginUser.user.currentHospital.id
		}
   //  uni.showLoading({
   //    title: "加载中",
   //    mask: true,
   //  });
   //  let postData = {
   //    "idx": 0,
   //    "sum": 9999,
			// parent:{id:loginUserStore.loginUser.user.currentHospital.id}
   //  };
    // 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(!incidentBuildStore.incidentBuild.data){
        //   if(loginUserStore.loginUser.user.duty){
        //     // 当前的所属责任科室
        //     incidentData.branch = loginUserStore.loginUser.user.duty.branch;
        //   }else if(loginUserStore.loginUser.user.branch){
        //     // 当前的所属院区
        //     incidentData.branch = loginUserStore.loginUser.user.branch.id;
        //   }
        // }

    //   }else{
    //     uni.showToast({
    //       icon: 'none',
    //       title: res.msg || '请求数据失败！'
    //     });
    //   }
    // })
  }

  // 获取故障来源列表
  function getSources(){
    uni.showLoading({
      title: "加载中",
      mask: true,
    });
    let postData = {
      "key": 'incident_source',
      "type": "list",
    };
    api_getDictionary(postData).then(res => {
      uni.hideLoading();
      res = res || [];
      dataInfo.sourceList = res.map(v => ({
        text: v.name,
        value: v.id,
        key: v.value,
      }));
      let discover = dataInfo.sourceList.find(v => v.key === 'leader');
      if(discover){
        incidentData.source = discover.value;
      }
    })
  }

  // 获取优先级列表
  function getPrioritys(){
    uni.showLoading({
      title: "加载中",
      mask: true,
    });
    let postData = {
      priority: {},
      idx: 0,
      sum: 9999,
    };
		getFetchDataList("simple/data", "priority", postData)
		  .then((data) => {
				uni.hideLoading();
		    dataInfo.priorityList = data.list.map(v => ({
		      text: v.name,
		      value: v.id,
		    }));
		  });
  }

  // 选择院区
  function changeBranch(){
    incidentData.department = undefined;
    incidentData.contactsInformation = '';
    incidentData.place = undefined;
    incidentData.houseNumber = undefined;
  }
	
  // 处理提交事件
  function handlerOrder(){
    let postData = {
      incident: dataInfo.incidentData,
    }
    postData.incident.handleDescription = dataInfo.handleDescription;
    postData.incident.handleCategory = {id: dataInfo.handleCategory};
    postData.incident.closecode = {id: dataInfo.closecode};
    postData.incident.category = dataInfo.category;
    postData.incident.synergetic = dataInfo.synergetic;

    return api_incidentTask('accept', postData);
  }

  // 报修图片
  function handlerOrderImg(imgObj){
    return uploadFile(imgObj, 'incident', dataInfo.incidentId)
  }
	
	// 获取优先级
	function getPriorityData(){
		let postData = {
			idx: 0,
			sum: 9999,
			incidentCategoryConfig: {
				categoryId: incidentData.category.id,
				dutyId: loginUserStore.loginUser.user.currentHospital.id,
			},
		};
		getFetchDataList("simple/data", "incidentCategoryConfig", postData).then(res => {
			let item = res.list.find(i=>i.categoryId == incidentData.category.id) 
			incidentData.priority = item.priority
		})
	}
	
  // 提交
  function submit(){
    isSubmit.value = true;
    if(!incidentData.branch){
      uni.showToast({
      	icon: 'none',
        title: '请选择院区'
      });
      return;
    }

    if(!incidentData.department){
      uni.showToast({
      	icon: 'none',
        title: '请选择报修科室'
      });
      return;
    }

    if(!incidentData.contactsInformation.trim()){
      uni.showToast({
      	icon: 'none',
        title: '请填写联系电话'
      });
      return;
    }

    if(!incidentData.category){
      uni.showToast({
      	icon: 'none',
        title: '请选择故障现象'
      });
      return;
    }

    if(!incidentData.source){
      uni.showToast({
      	icon: 'none',
        title: '请选择故障来源'
      });
      return;
    }

    if(!incidentData.priority){
      uni.showToast({
      	icon: 'none',
        title: '请选择优先级'
      });
      return;
    }

    if(!incidentData.description.trim()){
      uni.showToast({
      	icon: 'none',
        title: '请填写故障描述'
      });
      return;
    }
    // 处理责任科室
    if(incidentData.category.branchType == 1){
      // 分院区
      if(incidentData.branch){
        let dutyConfig = incidentData.category.branchUserGroups.find(v=>v.branchId == incidentData.branch);
        if(dutyConfig && dutyConfig.dutyId && dutyConfig.dutyName){
          incidentData.duty = {id:dutyConfig.dutyId,dept:dutyConfig.dutyName};
        }else{
          incidentData.duty = undefined;
        }
      }else{
        incidentData.duty = undefined;
      }
    }else{
      // 不分院区
      incidentData.duty = incidentData.category.dutyDepartment;
    }
    incidentData.title = incidentData.category.category;
    incidentBuildStore.setIncidentBuildData(incidentData, 'buildIncident');
    uni.navigateTo({
      url: '/pages/assign/assign'
    })
  }

  onLoad((option) => {
    handlerStore.clearHandlerData();
    if(incidentBuildStore.incidentBuild.data){
      Object.assign(
        incidentData,
        incidentBuildStore.incidentBuild.data,
        {
          priority: incidentBuildStore.incidentBuild.data.category ? (incidentBuildStore.incidentBuild.data.category.priority ? incidentBuildStore.incidentBuild.data.category.priority.id : undefined) : undefined,
          description: incidentBuildStore.incidentBuild.data.category ? incidentBuildStore.incidentBuild.data.category.mutiCategory : undefined,
        },
      );
      // 修改报修科室,则回显楼栋,楼层,详细地址,联系电话
      if(incidentBuildStore.incidentBuild.sign === 'department'){
				if(incidentData.department){
					incidentData.place = incidentData.department || undefined;
					incidentData.houseNumber = incidentData.department.address || '';
					incidentData.contactsInformation = incidentData.department.manyPhone ? incidentData.department.manyPhone.split(',')[0] : '';
				}
      }
			if(incidentData.category && incidentData.category.id){
				getPriorityData()
			}
    }
    getBranchs();
    getSources();
    getPrioritys();
  })
</script>

<style lang="scss" scoped>
.buildIncident{
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .body{
    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;
        flex-shrink: 0;
        &.select{
          width: calc(5em + 20rpx);
        }
      }
      .value{
        width: 100%;
        &.category{
          width: 100%;
          display: flex;
          justify-content: space-between;
          align-items: center;
          .categoryName{
            font-size: 26rpx;
            color: #555;
            flex: 1;
          }
          .newicon-weibiaoti2010104{
            color: $uni-primary;
            margin-left: 24rpx;
          }
        }
        .imgTips{
          color: #909399;
          font-size: 22rpx;
        }
      }
			.size-14{
				font-size: 26rpx;
			}
    }
  }
}
</style>
