<template>
  <view class="buildIncident">
    <scroll-view scroll-y class="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>
      </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">{{incidentData.place ? incidentData.place.area.area + ' ' + incidentData.place.place : ''}}</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>
      </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>
      </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>

    </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_branch, api_getDictionary, 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(){
    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(!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 === 'discover');
      if(discover){
        incidentData.source = discover.value;
      }
    })
  }

  // 获取优先级列表
  function getPrioritys(){
    uni.showLoading({
      title: "加载中",
      mask: true,
    });
    let postData = {
      "key": 'incident_priority',
      "type": "list",
    };
    api_getDictionary(postData).then(res => {
      uni.hideLoading();
      res = res || [];
      dataInfo.priorityList = res.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 submit(){
    isSubmit.value = true;
    console.log(dataInfo);
    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;
    }
    console.log(incidentData);

    // 处理责任科室
    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'){
        incidentData.place = incidentData.department.place || undefined;
        incidentData.houseNumber = incidentData.department.address || '';
        incidentData.contactsInformation = incidentData.department.phone ? incidentData.department.phone.split(',')[0] : '';
      }
    }
    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;
        }
      }
    }
  }
}
</style>
