<template>
  <view class="handler">
    <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>
		<view class="body view-body" :class="{ page_padding: !(dataInfo.tabActiveValue === 'doing' && isInSummaryOrder), bg: (dataInfo.tabActiveValue === 'doing' && isInSummaryOrder) }">
    <!-- <scroll-view scroll-y class="body" :class="{ page_padding: !(dataInfo.tabActiveValue === 'doing' && isInSummaryOrder), bg: (dataInfo.tabActiveValue === 'doing' && isInSummaryOrder) }"> -->
      <!-- 汇总单 -->
      <template v-if="dataInfo.tabActiveValue === 'doing' && isInSummaryOrder">
        <!-- 耗材 -->
        <view class="summaryItem">
          <view class="summaryItem_head">
            耗材清单
          </view>
          <view class="summaryItem_body" v-if="dataInfo.summaryObj.consumableList.length">
            <view class="summaryItem_bodyItem" v-for="item in dataInfo.summaryObj.consumableList" :key="item.id" @click="numberClick(item, 'editConsumable')">
              <view class="summaryItem_bodyItem_top">
                <text class="name ellipsis">{{ item.consumableName }}<template v-if="item.consumableBrandModel">({{ item.consumableBrandModel }})</template></text>
                <text class="value">{{ item.consumableEndPrice }}元</text>
              </view>
              <view class="summaryItem_bodyItem_bottom">
                <text class="name">x{{ item.consumablesNum }}{{ item.consumablesUnit }}</text>
                <text class="value">总价{{item.consumablesNum * item.consumableEndPrice}}元</text>
              </view>
            </view>
          </view>
          <view class="summaryItem_foot">
            <view class="summaryItem_foot_total">
              耗材总价：{{dataInfo.summaryObj.consumablePrice}}元
            </view>
            <view class="summaryItem_foot_add" @click="addConsumable">
              <text class="newicon newicon-icon-test"></text>
            </view>
          </view>
        </view>
        
        <!-- 工时 -->
        <view class="summaryItem">
          <view class="summaryItem_head">
            工时清单
          </view>
          <view class="summaryItem_body" v-if="dataInfo.summaryObj.workHourManagementList.length">
            <view class="summaryItem_bodyItem" v-for="item in dataInfo.summaryObj.workHourManagementList" :key="item.id" @click="numberClick(item, 'editWorkHourManagement')">
              <view class="summaryItem_bodyItem_top">
                <text class="name ellipsis">{{ item.workName }}</text>
                <text class="value">{{ item.wage }}元</text>
              </view>
              <view class="summaryItem_bodyItem_bottom">
                <text class="name">x{{ item.workHourNum2 }}{{ item.workUnit }}</text>
                <text class="value">总价{{item.workHourNum2 * item.wage}}元</text>
              </view>
            </view>
          </view>
          <view class="summaryItem_foot">
            <view class="summaryItem_foot_total">
              工时总价：{{dataInfo.summaryObj.workHourPrice}}元
            </view>
            <view class="summaryItem_foot_add" @click="addWorkHourManagement">
              <text class="newicon newicon-icon-test"></text>
            </view>
          </view>
        </view>
        
        <!-- 汇总单总价 -->
        <view class="summaryItem">
          <view class="summaryItem_foot total">
            <view class="summary_total">
              汇总单总价：{{dataInfo.summaryObj.totalMaintenancePrice}}元
            </view>
          </view>
        </view>
      </template>
      
      <!-- 故障处理 -->
      <template v-if="dataInfo.tabActiveValue === 'doing' && !isInSummaryOrder">
        <view class="form_item column" v-if="dataInfo.category.hasSimple != 1">
          <view class="title title-width">
						<text class="required newicon newicon-bitian"></text>
						<view class="title-fl-sb">
							解决方案：
							<view @click="importRep('malfunction')" class="import-rep">引入知识库({{dataInfo.introduceCount}})</view>
						</view>	
					</view>
          <uni-easyinput id="scheme" class="value" type="textarea" v-model="dataInfo.handleDescription" placeholder="请输入解决方案" :class="{formRed: isSubmit && !dataInfo.handleDescription.trim()}" />
        </view>
        <view class="form_item" v-if="dataInfo.category.hasSimple != 1">
          <view class="title"><text class="required newicon newicon-bitian"></text>故障现象：</view>
          <view class="value category" @click="selectCategory">
            <text class="categoryName ellipsis-multiline">{{dataInfo.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 class="value" v-model="dataInfo.handleCategory" :localdata="dataInfo.handleCategoryList" :clear="false" placeholder="请选择处理方式" :class="{formRed: isSubmit && !dataInfo.handleCategory}"></uni-data-select> -->
					<uni-data-picker class="value" placeholder="请选择处理方式"
						v-model="dataInfo.handleCategory" :localdata="dataInfo.handleCategoryList"
						:clear-icon="false" :class="{formRed: isSubmit && !dataInfo.handleCategory}">
					</uni-data-picker>
				</view>
        <view class="form_item" v-if="dataInfo.category.hasSimple != 1">
          <view class="title select"><text class="required newicon newicon-bitian"></text>处理结果：</view>
          <!-- <uni-data-select class="value" v-model="dataInfo.closecode" :localdata="dataInfo.closecodeList" :clear="false" placeholder="请选择处理结果" :class="{formRed: isSubmit && !dataInfo.closecode}"></uni-data-select> -->
					<uni-data-picker class="value" placeholder="请选择处理结果"
						v-model="dataInfo.closecode" :localdata="dataInfo.closecodeList"
						:clear-icon="false" :class="{formRed: isSubmit && !dataInfo.closecode}">
					</uni-data-picker>
				</view>
        <view class="form_item">
          <view class="title"><text class="required newicon newicon-bitian transparent"></text>协同人员：</view>
          <text class="synergeticNames ellipsis">{{dataInfo.synergetic.map(v => v.name).join('，')}}</text>
          <button type="primary" plain size="mini" class="primaryPlainButton synergeticAdd" @click="synergeticAdd">+立即添加</button>
        </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="dataInfo.handlerImgList" 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>
      </template>
      
      <!-- 延期处理 -->
      <template v-if="dataInfo.tabActiveValue === 'overtime'">
        <view class="form_item">
          <view class="title select"><text class="required newicon newicon-bitian"></text>延期原因：</view>
          <!-- <uni-data-select class="value" v-model="dataInfo.repairTypeId" :localdata="dataInfo.repairTypeList" :clear="false" placeholder="请选择延期原因" :class="{formRed: isSubmit && !dataInfo.repairTypeId}"></uni-data-select> -->
					<uni-data-picker class="value" placeholder="请选择延期原因"
						v-model="dataInfo.repairTypeId" :localdata="dataInfo.repairTypeList"
						:clear-icon="false" :class="{formRed: isSubmit && !dataInfo.repairTypeId}">
					</uni-data-picker>
				</view>
        <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.deferralRemark" placeholder="请输入延期说明" :class="{formRed: isSubmit && !dataInfo.deferralRemark.trim()}" />
        </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.deferralDayId" :localdata="dataInfo.deferralDayList" :clear="false" placeholder="请选择延期天数" :class="{formRed: isSubmit && !dataInfo.deferralDayId}"></uni-data-select> -->
					<uni-data-picker class="value" placeholder="请选择延期天数"
						v-model="dataInfo.deferralDayId" :localdata="dataInfo.deferralDayList"
						:clear-icon="false" :class="{formRed: isSubmit && !dataInfo.deferralDayId}">
					</uni-data-picker>
				</view>
      </template>
    <!-- </scroll-view> -->
		</view>
    <view class="foot_common_btns">
      <button @click="goBackOrToList" type="default" class="cancelButton btn">{{dataInfo.isSummaryNext ? '上一步' : '返回'}}</button>
      <button @click="submit" type="default" class="primaryButton btn">{{dataInfo.tabActiveValue === 'doing' && isInSummaryOrder ? '下一步' : '提交'}}</button>
    </view>
    <NumberModal v-if="dataInfo.isNumber" @cancelEmit="cancelNumber" @confirmEmit="conformNumber" @removeEmit="removeNumber" :selectData="dataInfo.selectData" :selectType="dataInfo.selectType" :evtNumber="dataInfo.evtNumber" showRemove></NumberModal>
  </view>
</template>

<script setup>
  import { ref, reactive, computed } from 'vue'
  import NumberModal from '@/components/NumberModal.vue';
  import { onLoad } from '@dcloudio/uni-app'
  import { generateNumberArray } from '@/utils/index.js'
  import { api_group, api_incidentDetail, api_user, api_incidentTask, api_branch, api_dutyDepartment, api_getDictionary, api_querySummaryDoc, api_addSummaryDoc } from "@/http/api.js"
  import { defaultColor } from '@/static/js/theme.js'
  import { useSetTitle } from '@/share/useSetTitle.js'
  import { useMakePhoneCall } from '@/share/useMakePhoneCall.js'
  import { useUploadFile } from '@/share/useUploadFile.js'
  import { useGoBack } from '@/share/useGoBack.js'
  import { useLoginUserStore } from '@/stores/loginUser'
  import { useHandlerStore } from '@/stores/handler'
  
  useSetTitle();
  const loginUserStore = useLoginUserStore();
  const handlerStore = useHandlerStore();
  const { makePhoneCall }  = useMakePhoneCall();
  const { uploadFile }  = useUploadFile();
  const { goBack }  = useGoBack();
  
  // 主题颜色
  const primaryColor = ref(defaultColor)
  
  // 数据
  const dataInfo = reactive({
    tabs: [
      // {id: 5, name: '故障处理', value: 'doing', num: ''},
      // {id: 6, name: '延期处理', value: 'overtime', num: ''},
    ],
    tabActiveValue: 0,//当前选择的tab
    incidentId: undefined,//事件ID
    incidentData: {},//事件对象
    repairTypeList: [], //延期原因列表
    repairTypeId: undefined, //延期原因ID
    deferralDayList: [], //延期天数列表
    deferralDayId: undefined, //延期天数ID
    deferralRemark: '',//延期说明
    summaryObj: {
      consumableList: [],//耗材列表
      workHourManagementList: [],//工时列表
    },//汇总单信息
    summaryId: undefined,//汇总单Id
    isNumber: false,//修改数量弹窗
    evtNumber: 1,//弹窗返回的数量
    selectData: {},//选择的对象
    selectType: {},//选择的对象类型
    handleDescription: '',//解决方案
    handleCategory: undefined,//处理方式
    handleCategoryList: [],//处理方式列表
    closecode: undefined,//处理结果
    closecodeList: [],//处理结果列表
    handlerImgList: [],//处理图片列表
    category: {},//故障现象
    synergetic: [],//协同人员
    isSummaryNext: false,//汇总单-下一步
		introduceCount :0 //引入次数
  })
  
	// 知识库id
	const solutionId = ref(null)
	
  // 是否提交
  const isSubmit = ref(false)
  
  // 处理图片
  const handlerImgRef = ref(null)
  
  // 是否进入汇总单
  const isInSummaryOrder = computed(() => {
    return dataInfo.tabActiveValue === 'doing' && dataInfo.incidentData.duty && dataInfo.incidentData.duty.addSummary == 1 && (dataInfo.incidentData.handlingPersonnelUser.id == loginUserStore.loginUser.user.id);
  })
  
  // 上一步或者返回列表
  function goBackOrToList(){
    if(dataInfo.isSummaryNext){
      goBack();
    }else{
      uni.reLaunch({
        url: '/pages/incidentList/incidentList'
      })
    }
  }
  
  // 上传处理图片成功
  function handlerImgSuccess(e){
    dataInfo.handlerImgList.forEach(v => {
      v.url = v.path;
    })
    console.log(dataInfo.handlerImgList);
    let handlerOrder$ = handlerOrder();
    let requestList = [handlerOrder$];
    dataInfo.handlerImgList.forEach(v => {
      let handlerOrderImg$ = handlerOrderImg(v);
      requestList.push(handlerOrderImg$);
    })
    
    Promise.all(requestList).then(resList => {
      uni.hideLoading();
      console.log(resList);
      if(resList[0].state == 200){
        uni.showToast({
        	icon: 'none',
          title: '处理成功',
          mask: true,
        });
        setTimeout(() => {
          uni.reLaunch({
            url: '/pages/incidentList/incidentList',
          })
        }, 1500)
      }else{
        uni.showToast({
          icon: 'none',
          title: resList[0].msg || '请求数据失败！'
        });
      }
    })
  }
  
  // 上传处理图片失败
  function handlerImgFail(e){
    dataInfo.handlerImgList.forEach(v => {
      v.url = v.path;
    })
    console.log(dataInfo.handlerImgList);
  }
  
  // 选择上传图片
  function handlerImgSelect(e){
    dataInfo.handlerImgList = dataInfo.handlerImgList.concat(e.tempFiles);
    console.log(dataInfo.handlerImgList);
  }
  
  // 删除上传图片
  function handlerImgDelete(e){
    dataInfo.handlerImgList = dataInfo.handlerImgList.filter(v => e.tempFile.uuid != v.uuid);
    console.log(dataInfo.handlerImgList);
  }
  
  // 添加协同人员
  function synergeticAdd(){
    handlerStore.setHandlerData(dataInfo, 'handler');
    uni.navigateTo({
      url: `/pages/synergeticAdd/synergeticAdd?incidentId=${dataInfo.incidentId}`
    })
  }
  
	// 引入知识库
	function importRep(type){
		uni.navigateTo({
		  url: `/pages/repository/repository?incidentId=${dataInfo.incidentId}&operateType=${type}`
		})
	}
	
  // 选择故障现象
  function selectCategory(){
    handlerStore.setHandlerData(dataInfo, 'handler');
    uni.navigateTo({
      url: `/pages/categoryOne/categoryOne?incidentId=${dataInfo.incidentId}`
    })
  }
  
  // 点击修改数量
  function numberClick(data, type){
    if(type === 'editConsumable'){
      dataInfo.evtNumber = data.consumablesNum;
    }else if(type === 'editWorkHourManagement'){
      dataInfo.evtNumber = data.workHourNum2;
    }
    
    dataInfo.isNumber = true;
    dataInfo.selectData = data;
    dataInfo.selectType = type;
  }
  
  // 确认修改数量
  function conformNumber(evtNumber){
    dataInfo.evtNumber = evtNumber;
    dataInfo.isNumber = false;
    addSummaryDoc();
  }
  
  // 移除数量
  function removeNumber(evtNumber){
    dataInfo.evtNumber = evtNumber;
    dataInfo.isNumber = false;
    removeSummaryDoc();
  }
  
  // 关闭修改数量
  function cancelNumber(){
    dataInfo.isNumber = false;
  }
  
  // 修改耗材/工时
  function addSummaryDoc(){
    uni.showLoading({
      title: "加载中",
      mask: true,
    });
    let postData = {
      "summaryId": dataInfo.summaryId,
      "modifyNum": 'edit',
    };
    if(dataInfo.selectType === 'editConsumable'){
      postData.consumableList = [
        {
          "consumablesId": dataInfo.selectData.consumableId,
          "consumablesNum": dataInfo.evtNumber,
        }
      ];
    }else if(dataInfo.selectType === 'editWorkHourManagement'){
      postData.workHourManagementList = [
        {
          "workHourId": dataInfo.selectData.id,
          "workHourNum": dataInfo.evtNumber,
        }
      ];
    }
    api_addSummaryDoc(postData).then(res => {
      uni.hideLoading();
      if(res.status == 200){
        uni.showToast({
        	icon: 'none',
          title: '修改数量成功',
          mask: true,
        });
        getSummaryList();
      }else{
        uni.showToast({
          icon: 'none',
          title: res.msg || '请求数据失败！'
        });
      }
    })
  }
  
  // 移除耗材/工时
  function removeSummaryDoc(){
    uni.showLoading({
      title: "加载中",
      mask: true,
    });
    let postData = {
      "summaryId": dataInfo.summaryId,
      "remove": 'remove',
    };
    if(dataInfo.selectType === 'editConsumable'){
      postData.consumableList = [
        {
          "consumablesId": dataInfo.selectData.consumableId,
          "consumablesNum": dataInfo.evtNumber,
        }
      ];
    }else if(dataInfo.selectType === 'editWorkHourManagement'){
      postData.workHourManagementList = [
        {
          "workHourId": dataInfo.selectData.id,
          "workHourNum": dataInfo.evtNumber,
        }
      ];
    }
    api_addSummaryDoc(postData).then(res => {
      uni.hideLoading();
      if(res.status == 200){
        uni.showToast({
        	icon: 'none',
          title: '移除成功',
          mask: true,
        });
        getSummaryList();
      }else{
        uni.showToast({
          icon: 'none',
          title: res.msg || '请求数据失败！'
        });
      }
    })
  }
  
  // 重置
  function reset(){
    dataInfo.repairTypeList = []; //延期原因列表
    dataInfo.repairTypeId = undefined; //延期原因ID
    dataInfo.deferralDayList = []; //延期天数列表
    dataInfo.deferralDayId = undefined; //延期天数ID
    dataInfo.deferralRemark = '';//延期说明
    dataInfo.summaryObj = {
      consumableList: [],//耗材列表
      workHourManagementList: [],//工时列表
    };//汇总单信息
    dataInfo.summaryId = undefined;//汇总单Id
    dataInfo.isNumber = false;//修改数量弹窗
    dataInfo.evtNumber = 1;//弹窗返回的数量
    dataInfo.selectData = {};//选择的对象
    dataInfo.selectType = {};//选择的对象类型
    dataInfo.handleDescription = '';//解决方案
    dataInfo.handleCategory = undefined;//处理方式
    dataInfo.handleCategoryList = [];//处理方式列表
    dataInfo.closecode = undefined;//处理结果
    dataInfo.closecodeList = [];//处理结果列表
    dataInfo.handlerImgList = [];//处理图片列表
    dataInfo.category = {};//故障现象
    dataInfo.synergetic = [];//协同人员
  }
  
  // 初始化表单
  function initForm(){
    if(dataInfo.tabActiveValue === 'doing' && isInSummaryOrder.value){
      getSummaryList();
    }else if(dataInfo.tabActiveValue === 'doing' && !isInSummaryOrder.value){
      getHandleCategorys();
      getClosecodes();
    }else if(dataInfo.tabActiveValue === 'overtime'){
      getRepairTypes();
      getDeferralDays();
    }
  }
  
  // 点击tab
  function clickTab(tabValue){
    if(dataInfo.tabActiveValue == tabValue){
      return;
    }
    dataInfo.tabActiveValue = tabValue;
    isSubmit.value = false;
    reset();
    dataInfo.category = dataInfo.incidentData.category || {};
    dataInfo.synergetic = dataInfo.incidentData.synergetic || [];
    initForm();
  }
  
  // 获取事件详情
  function getIncidentDetail(){
    uni.showLoading({
      title: "加载中",
      mask: true,
    });

    api_incidentDetail(dataInfo.incidentId).then(res => {
      uni.hideLoading();
      if(res.status == 200){
        dataInfo.incidentData = res.data || {};
        
        if(dataInfo.isSummaryNext){
          // 汇总单-下一步
          dataInfo.incidentData.duty.addSummary = 0;
        }
        
        // 跳转页面选择了选项并且工单ID一致
        if(handlerStore.handler.data && handlerStore.handler.data.incidentId == dataInfo.incidentId){
          Object.assign(dataInfo, handlerStore.handler.data);
          console.log(dataInfo)
          handlerStore.clearHandlerData();
        }else{
          handlerStore.clearHandlerData();
          // 初始化回显
          dataInfo.category = dataInfo.incidentData.category || {};
          dataInfo.synergetic = dataInfo.incidentData.synergetic || [];
          
          let chuli = false;//故障处理权限
          for (let i = 0; i < loginUserStore.loginUser.menu.length; i++) {
              if (loginUserStore.loginUser.menu[i].link == "shijianliebiao_chuli") {
                chuli = true
              }
          }
          
          // 故障处理
          if(dataInfo.incidentData.state.value == 'handler' && dataInfo.incidentData.handlingPersonnelUser && dataInfo.incidentData.handlingPersonnelUser.id == loginUserStore.loginUser.user.id && chuli){
            let flag = dataInfo.tabs.some(v => v.value === 'doing');
            !flag && dataInfo.tabs.splice(0, 0, {id: 5, name: '故障处理', value: 'doing', num: ''});
          }
          
          // 延期处理
          if(dataInfo.incidentData.state.value == 'handler' && dataInfo.incidentData.handlingPersonnelUser && dataInfo.incidentData.handlingPersonnelUser.id == loginUserStore.loginUser.user.id){
            let flag = dataInfo.tabs.some(v => v.value === 'overtime');
            !flag && dataInfo.tabs.push({id: 6, name: '延期处理', value: 'overtime', num: ''});
          }
          
          dataInfo.tabActiveValue = dataInfo.tabs[0].value;
        }
        
        initForm()
      }else{
        uni.showToast({
          icon: 'none',
          title: res.msg || '请求数据失败！'
        });
      }
    })
  }
  
  // 获取延期原因列表
  function getRepairTypes(){
    uni.showLoading({
      title: "加载中",
      mask: true,
    });
    let postData = {
      "key": 'repair_type',
      "type": "list",
    };
    api_getDictionary(postData).then(res => {
      uni.hideLoading();
      res = res || [];
      dataInfo.repairTypeList = res.map(v => ({
        text: v.name,
        value: v.id,
      }));
    })
  }
  
  // 获取处理方式列表
  function getHandleCategorys(){
    uni.showLoading({
      title: "加载中",
      mask: true,
    });
    let postData = {
      "key": 'incident_handleCategory',
      "type": "list",
    };
    api_getDictionary(postData).then(res => {
      uni.hideLoading();
      res = res || [];
      dataInfo.handleCategoryList = res.map(v => ({
        text: v.name,
        value: v.id,
        key: v.value,
      }));
      if(!dataInfo.handleCategory){
        let handleCategory = dataInfo.handleCategoryList.find(v => v.key == 'SUPPORT');
        dataInfo.handleCategory = handleCategory ? handleCategory.value : undefined;
      }
    })
  }
  
  // 获取处理结果列表
  function getClosecodes(){
    uni.showLoading({
      title: "加载中",
      mask: true,
    });
    let postData = {
      "key": 'incident_closecode',
      "type": "list",
    };
    api_getDictionary(postData).then(res => {
      uni.hideLoading();
      res = res || [];
      dataInfo.closecodeList = res.map(v => ({
        text: v.name,
        value: v.id,
        key: v.value,
      }));
      if(!dataInfo.closecode){
        let closecode = dataInfo.closecodeList.find(v => v.key == '060');
        dataInfo.closecode = closecode ? closecode.value : undefined;
      }
    })
  }
  
  // 获取延期天数列表
  function getDeferralDays(){
    dataInfo.deferralDayList = generateNumberArray(1, 15).map(v => ({
      text: v + '天',
      value: v,
    }));
  }
  
  // 获取汇总单信息
  function getSummaryList(){
    uni.showLoading({
      title: "加载中",
      mask: true,
    });
    let postData = {
      "incidentId": dataInfo.incidentId,
    };
    api_querySummaryDoc(postData).then(res => {
      uni.hideLoading();
      if(res.status == 200){
        dataInfo.summaryObj = {...{consumableList:[], workHourManagementList: []}, ...res };
        console.log(dataInfo.summaryObj)
        dataInfo.summaryId = res.summaryId;
      }else if(res.status == 201){
        // 事件第一次绑定汇总单
        dataInfo.summaryId = res.summaryId;
      }else{
        uni.showToast({
          icon: 'none',
          title: res.msg || '请求数据失败！'
        });
      }
    })
  }
  
  // 添加耗材
  function addConsumable(){
    uni.navigateTo({
      url: `/pages/consumableList/consumableList?incidentId=${dataInfo.incidentId}&summaryId=${dataInfo.summaryId}`
    })
  }
  
  // 添加工时
  function addWorkHourManagement(){
    uni.navigateTo({
      url: `/pages/workHourManagementOne/workHourManagementOne?incidentId=${dataInfo.incidentId}&summaryId=${dataInfo.summaryId}`
    })
  }
  
  // 提交
  function submit(){
    isSubmit.value = true;
    if(dataInfo.tabActiveValue === 'doing' && isInSummaryOrder.value){
      uni.navigateTo({
        url: `/pages/handler/handler?incidentId=${dataInfo.incidentId}&isSummaryNext=1`,
      });
    }else if(dataInfo.tabActiveValue === 'doing' && !isInSummaryOrder.value){
      submitHandler();
    }else if(dataInfo.tabActiveValue === 'overtime'){
      submitOvertime();
    }
  }
  
  // 处理提交事件
  function handlerOrder(){
    let postData = {
      incident: dataInfo.incidentData,
			solutionId:solutionId.value
    }
    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(dataInfo.tabActiveValue, postData);
  }
  
  // 处理图片
  function handlerOrderImg(imgObj){
    return uploadFile(imgObj, 'incident', dataInfo.incidentId)
  }
  
  // 处理提交
  function submitHandler(){
    console.log(dataInfo);
    if(!dataInfo.handleDescription.trim() && dataInfo.category.hasSimple != 1){
      uni.showToast({
      	icon: 'none',
        title: '请填写解决方案'
      });
      return;
    }
    
    if(!dataInfo.category.id && dataInfo.category.hasSimple != 1){
      uni.showToast({
      	icon: 'none',
        title: '请选择故障现象'
      });
      return;
    }
    
    if(!dataInfo.handleCategory){
      uni.showToast({
      	icon: 'none',
        title: '请选择处理方式'
      });
      return;
    }
    
    if(!dataInfo.closecode && dataInfo.category.hasSimple != 1){
      uni.showToast({
      	icon: 'none',
        title: '请选择处理结果'
      });
      return;
    }
    console.log(dataInfo.handlerImgList)
    
    uni.showLoading({
      title: "加载中",
      mask: true,
    });
    if(dataInfo.handlerImgList.length){
      // 有图片
      handlerImgRef.value.upload();
    }else{
      // 没有图片
      let handlerOrder$ = handlerOrder();
      let requestList = [handlerOrder$];
      Promise.all(requestList).then(resList => {
        uni.hideLoading();
        console.log(resList);
        if(resList[0].state == 200){
          uni.showToast({
          	icon: 'none',
            title: '处理成功',
            mask: true,
          });
          setTimeout(() => {
            uni.reLaunch({
              url: '/pages/incidentList/incidentList',
            })
          }, 1500)
        }else{
          uni.showToast({
            icon: 'none',
            title: resList[0].msg || '请求数据失败！'
          });
        }
      })
    }
  }
  
  // 延期处理提交
  function submitOvertime(){
    if(!dataInfo.repairTypeId){
      uni.showToast({
      	icon: 'none',
        title: '请选择延期原因'
      });
      return;
    }
    
    if(!dataInfo.deferralRemark.trim()){
      uni.showToast({
      	icon: 'none',
        title: '请填写延期说明'
      });
      return;
    }
    
    if(!dataInfo.deferralDayId){
      uni.showToast({
      	icon: 'none',
        title: '请选择延期天数'
      });
      return;
    }
    
    uni.showLoading({
      title: "加载中",
      mask: true,
    });
    
    let postData = {
      incident: dataInfo.incidentData,
    }
    
    postData.incident.currentLog = {
      remark: dataInfo.deferralRemark,
      extra1: dataInfo.repairTypeId,
      extra2: dataInfo.deferralDayId,
    }
    
    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 getHtml(html) {
	  const tempDiv = document.createElement('div');
	  tempDiv.innerHTML = html;
	  return tempDiv.textContent || tempDiv.innerText || '';
	}
	
  onLoad((option) => {
		if(option.type&&decodeURIComponent(option.type=='rep')){
			let handleDescription = decodeURIComponent(option.handleDescription)
			solutionId.value = JSON.parse(decodeURIComponent(option.solutionId))
			dataInfo.introduceCount = decodeURIComponent(option.introduceCount!="undefined"?option.introduceCount:0)
			if(handleDescription!='undefined'){
				dataInfo.handleDescription = getHtml(handleDescription);
			}
		}
    dataInfo.incidentId = JSON.parse(decodeURIComponent(option.incidentId))
    dataInfo.isSummaryNext = option.isSummaryNext == 1;
    getIncidentDetail();
  })
</script>

<style lang="scss" scoped>
.handler{
  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;
    box-sizing: border-box;
    flex: 1;
    min-height: 0;
    &.bg{
      background-color: #F7F7F7;
    }
    .summaryItem{
      &:first-of-type{
        .summaryItem_head{
          border-bottom: 1rpx solid #DDDDDD;
        }
      }
      .summary_total{
        padding: 20rpx 0;
        display: flex;
        justify-content: center;
        align-items: center;
      }
      .summaryItem_head{
        padding: 24rpx;
        font-size: 26rpx;
        color: #3A3A3A;
      }
      .summaryItem_body{
        font-size: 30rpx;
        background-color: #fff;
        .summaryItem_bodyItem{
          padding: 24rpx;
          border-bottom: 1rpx solid #DDDDDD;
          .summaryItem_bodyItem_top{
            display: flex;
            justify-content: space-between;
            align-items: center;
            .value{
              padding-left: 48rpx;
              flex-shrink: 0;
            }
          }
          .summaryItem_bodyItem_bottom{
            margin-top: 24rpx;
            display: flex;
            justify-content: space-between;
            align-items: center;
            .name{
              text-align: right;
              flex: 1;
            }
            .value{
              width: 240rpx;
              text-align: right;
              padding-left: 48rpx;
              flex-shrink: 0;
            }
          }
        }
      }
      .summaryItem_foot{
        font-size: 30rpx;
        background-color: #fff;
        &.total{
          margin-top: 24rpx;
        }
        .summaryItem_foot_total{
          padding: 24rpx 0;
          display: flex;
          justify-content: center;
          align-items: center;
        }
        .summaryItem_foot_add{
          border-top: 1rpx solid #DDDDDD;
          padding: 24rpx 0;
          display: flex;
          justify-content: center;
          align-items: center;
          .newicon-icon-test{
            font-size: 30rpx;
            font-weight: bold;
          }
        }
      }
    }
    .form_item_column{
      padding-top: 24rpx;
      min-height: 86rpx;
      .form_item{
        padding-top: 0;
        min-height: auto;
      }
    }
    .form_item{
      display: flex;
      align-items: center;
      padding-top: 24rpx;
      min-height: 86rpx;
      &.column{
        height: auto;
        flex-direction: column;
        align-items: flex-start;
				.import-rep{
					padding: 5rpx 10rpx;
					border-radius: 50rpx;
					background: #d1fcd5;
					color: #49b856;
					font-size: 24rpx;
				}
        .title{
          margin-right: 0;
        }
				.title-width{
					width: 100%;
				}
				.title-fl-sb{
					display: flex;
					justify-content: space-between;
					width: 100%;
				}
        .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;
        }
      }
      .synergeticNames{
        font-size: 26rpx;
        margin-right: 24rpx;
      }
      .synergeticAdd{
        flex-shrink: 0;
      }
    }
  }
}
</style>
