// pages/violationReporting/violationReporting.ts
import { getAction, upload, postAction, putAction } from '../../../api/base';
const dayjs = require('dayjs');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isSubmit: false,
    // 是否编辑
    isEdit: false,
    // 展开/收起
    showBox: {
      base: true,
      followInfo: true,
      inspectionInfo: true,
      feedbackInfo: true,
      handleInfo: true
    },
    // 内容勾选
    contentItem: {
      inspectionTask: false, // 车辆巡检
      opinion: false, // 意见反馈
      handle: false // 异常处理 巡检结果未不合格时
    },
    // 下拉选择/日期弹窗展示
    showList: {
      projectShow: false,
      reviewTypeShow: false,
      reviewTimeShow: false,
      resultStatusShow: false,
      inspectionResultShow: false,
      opinionTypeShow: false,
      userShow: false,
      reviewUserShow: false,
      customerFollowTemplateShow: false,
      inspectionTemplateShow: false,
      pleasedStatusShow: false,
      handleTypeShow: false,
      handleTimeShow: false
    },
    // 提交数据
    params: {
      id: '', // id
      projectId: '', // 项目id
      reviewType: '', // 回访方式
      reviewTime: '', // 回访时间
      remark: '', // 备注
      templateId: '', // 回访模板
      partList: '', // 模板数据、
      reviewUserId: '', // 回访人
      resultStatus: '', // 回访结果
      fileUrl: '', // 附件
      // 车辆巡检
      inspectionTask: {
        inspectionTemplateId: '', // 巡检模板
        inspectionResult: '', // 巡检结果
        remark: '', // 备注
        fileUrl: '',
        handlePlan: '', // 处理方案
        handleType: '', // 处理结果
        handleTime: '' // 处理时间
      },
      // 意见反馈
      opinion: {
        name: '', // 意见标题
        opinionType: '', // 意见分类
        proposeName: '', // 提议人
        phone: '', // 联系电话
        content: '', // 意见内容
        handleId: '', // 处理人
        fileUrl: '', // 附件
        remark: '' // 备注
      }
    },
    // 翻译回显
    dictTextList: {
      projectId_dictText: '', // 项目名
      reviewType_dictText: '', // 回访方式
      reviewTimeTamp: new Date().getTime(), // 回访时间
      handleTimeTamp: new Date().getTime(), // 处理时间
      reviewUserId_dictText: '', //回访人
      resultStatus_dictText: '', //回访结果
      inspectionResult_dictText: '', // 巡检结果
      opinionType_dictText: '', // 意见分类
      handleId_dictText: '', // 处理人
      customerFollowTemplate_dictText: '', // 回访模板
      inspectionTemplate_dictText: '', // 巡检模板
      handleType_dictText: '' // 处理结果
    },
    projectList: [], // 项目数据
    filterProjectList: [], // 过滤后项目数据
    projectSearchVal: '', // 项目查询
    userList: [], // 处理人数据
    reviewUserList: [], // 回访人数据
    filterUserList: [], // 过滤后处理人数据
    filterReviewUserList: [], // 过滤后回访人数据
    userSearchVal: '', // 项目查询
    reviewUserSearchVal: '', // 项目查询
    reviewTypeList: [], // 回访方式字典
    resultStatusList: [], // 回访结果字典
    opinionStatusList: [], // 回访结果字典（编辑状态用）
    inspectionResultList: [], // 巡检结果字典
    opinionTypeList: [], // 意见分类
    baseInfoFileList: [], // 回访信息附件
    inspectionTaskFileList: [], // 车辆巡检附件
    opinionFileList: [], // 意见反馈附件
    originVehicleList: [], // 项目所属车辆数据(原始数据，用于还原)
    vehicleList: [], // 项目所属车辆数据
    customerFollowTemplateList: [], // 客户回访模板数据
    filterCustomerFollowTemplateList: [], // 过滤后客户回访模板数据
    customerFollowTemplateSearchVal: '', // 回访模板查询
    inspectionTemplateList: [], // 车辆巡检模板数据
    filterInspectionTemplateList: [], // 过滤后车辆巡检模板数据
    inspectionTemplateSearchVal: '', // 巡检模板查询
    customerFollowTemplatePartList: [], // 修改格式后的回访模板
    inspectionTemplatePartList: [], // 修改格式后的巡检模板
    pleasedStatusList: [
      { text: '满意', value: '1' },
      { text: '不满意', value: '2' }
    ], // 满意度
    currentIndex: {}, // 选中的满意度序号
    // 必填校验
    requireObj: {
      baseInfo: {
        projectId: '', // 项目id
        reviewType: '', // 回访方式
        reviewTime: '', // 回访时间
        templateId: '', // 回访模板
        reviewUserId: '', // 回访人
        resultStatus: '' // 回访结果
      },
      inspectionTaskInfo: {
        inspectionResult: '', // 巡检结果
        inspectionTemplateId: '', // 巡检模板
        handlePlan: '', // 处理方案
        handleType: '', // 处理结果
        handleTime: '' // 处理时间
      },
      opinionInfo: {
        name: '', // 意见标题
        opinionType: '', // 意见分类
        proposeName: '', // 提议人
        phone: '', // 联系电话
        content: '', // 意见内容
        handleId: '' // 处理人
      }
    },
    // 非必填校验
    validateObj: {
      baseInfo: {
        remark: '', // 备注
        partList: [] // 模板备注
      },
      inspectionTaskInfo: {
        remark: '',
        partList: [], // 模板备注
        vehicles: [] //车辆备注
      },
      opinionInfo: {
        remark: ''
      }
    },
    uploading: false // 文件是否上传中
  },
  // 展示和收起
  showBoxInf(e: any) {
    let data: any = { ...this.data };
    let { fieldname } = e.currentTarget.dataset;
    // let detail = e.detail;
    data.showBox[fieldname] = !data.showBox[fieldname];
    this.setData(data);
  },
  // 选择内容
  selectContent(e: any) {
    if (this.data.isEdit) return;
    let data: any = { ...this.data };
    let { fieldname } = e.currentTarget.dataset;
    // let detail = e.detail;
    data.contentItem[fieldname] = !data.contentItem[fieldname];
    this.setData(data);
  },
  // 下拉选择/日期确认
  pickerConfirm(event: any) {
    //下拉框点击确认
    let { fieldname, dicttext, type } = event.currentTarget.dataset;
    let detail = event.detail;
    let data: any = { ...this.data };
    if (fieldname == 'reviewTime') {
      data.params[fieldname] = dayjs(new Date(detail)).format(
        'YYYY-MM-DD HH:mm:ss'
      );
      data.dictTextList.reviewTimeTamp = event.detail;
      data.requireObj.baseInfo.reviewTime = '';
    } else if (fieldname == 'handleTime') {
      data.params.inspectionTask[fieldname] = dayjs(new Date(detail)).format(
        'YYYY-MM-DD HH:mm:ss'
      );
      data.dictTextList.handleTimeTamp = event.detail;
      data.requireObj.inspectionTaskInfo.handleTime = '';
    } else {
      // 基础信息
      if (type) {
        data.params[type][fieldname] = detail.value.value;
        data.requireObj[type + 'Info'][fieldname] = '';
      }
      // 车辆巡检和意见反馈
      else {
        data.params[fieldname] = detail.value.value;
        data.requireObj.baseInfo[fieldname] = '';
      }
      data.dictTextList[dicttext] = detail.value.text;
    }
    if (fieldname == 'inspectionResult') {
      // 控制异常处理显隐
      if (event.detail.value.value == '0') {
        data.contentItem.handle = true;
      } else {
        data.contentItem.handle = false;
      }
    }
    // 根据项目获取车辆
    if (fieldname == 'projectId') {
      this.getVehicle(detail.value.value);
    }
    // 获取回访模板数据
    if (fieldname == 'templateId') {
      data.customerFollowTemplatePartList = this.changeTemplate(
        detail.value.partList,
        'categoryName',
        'followName',
        'pleasedStatus'
      );
      data.validateObj.baseInfo.partList = [];
      data.customerFollowTemplatePartList.forEach((item: any) => {
        let arr: any = [];
        for (let i = 0; i < item.length; i++) {
          arr.push({ remark: '' });
        }
        data.validateObj.baseInfo.partList.push(arr);
      });
    }
    // 获取巡检模板数据
    else if (fieldname == 'inspectionTemplateId') {
      data.inspectionTemplatePartList = this.changeTemplate(
        detail.value.partList,
        'name',
        'content',
        'normal'
      );
      data.validateObj.inspectionTaskInfo.partList = [];
      data.inspectionTemplatePartList.forEach((item: any) => {
        let arr: any = [];
        for (let i = 0; i < item.length; i++) {
          arr.push({ remark: '' });
        }
        data.validateObj.inspectionTaskInfo.partList.push(arr);
      });
    }

    this.setData(data);
    this.hidePicker();
  },
  // 选中满意度
  pleasedStatusPickerConfirm(event: any) {
    let data: any = this.data;
    data.customerFollowTemplatePartList[data.currentIndex.index][
      data.currentIndex.idx
    ].pleasedStatus = event.detail.value.value;
    this.setData(data);
    this.hidePicker();
  },
  // 是否正常单选
  templateOnChange(event: any) {
    let { index, idx } = event.currentTarget.dataset;
    let data: any = this.data;
    data.inspectionTemplatePartList[index][idx].normal = event.detail;
    this.setData(data);
  },
  // 巡检车辆结果单选
  vehicleOnChange(event: any) {
    let { index } = event.currentTarget.dataset;
    let data: any = this.data;
    data.vehicleList[index].isNormal = event.detail;
    this.setData(data);
  },
  // 车辆异常备注
  vehicleRemarkChange(event: any) {
    let { index } = event.currentTarget.dataset;
    let data: any = this.data;
    data.vehicleList[index].abnormalMsg = event.detail.value;
    let regex = /[!@#$%^&*?><|\\\\]/;
    let spaceRegex = new RegExp(/\s+/g);
    let message = '';
    // 有填写内容，校验特殊字符
    if (event.detail.value) {
      if (regex.test(event.detail.value)) {
        message = '不支持特殊字符';
      } else if (spaceRegex.test(event.detail.value))
        message = '不支持含有空格';
      else if (event.detail.value.length > 200)
        message = '输入长度不得超过200个字符';
    }
    data.validateObj.inspectionTaskInfo.vehicles[index].remark = message;
    this.setData(data);
  },
  // 删除车辆
  deleteVehicle(event: any) {
    let { index } = event.currentTarget.dataset;
    let data: any = this.data;
    data.vehicleList.splice(index, 1);
    data.validateObj.inspectionTaskInfo.vehicles.splice(index, 1);
    this.setData(data);
  },
  // 重置车辆
  resetVehicle() {
    let data: any = this.data;
    // 将删除的数据恢复
    data.originVehicleList.forEach((item: any, index: number) => {
      let res = data.vehicleList.some((el: any) => {
        return el.vehicleId == item.vehicleId;
      });
      if (!res) {
        data.vehicleList.splice(index, 0, item);
        data.validateObj.inspectionTaskInfo.vehicles.splice(index, 0, {
          remark: ''
        });
      }
    });
    this.setData(data);
  },
  // 模板数据格式修改(提交改为编辑)
  changeTemplate(data: any, name: string, childNmae: string, status: string) {
    let arr = [] as any;
    if (data.length > 0) {
      data.forEach((item: any) => {
        let res = {
          [name]: item[name],
          [childNmae]: item[childNmae],
          [status]: this.data.isEdit ? item[status] : '1',
          remark: this.data.isEdit ? item.remark : ''
        };
        // 没数据时，放第一位
        if (arr.length == 0) {
          arr.push([res]);
        }
        // 按某个字段分类模板
        else {
          let result = false;
          for (const el of arr) {
            // 存在相同数据
            if (el[0][name] == item[name]) {
              el.push(res);
              result = true;
              break;
            }
          }
          // 存在不同
          if (!result) {
            arr.push([res]);
          }
        }
      });
    }
    return arr;
  },
  // 模板数据格式修改(编辑改为提交)
  changeTemplate2(data: any) {
    let arr: any = [];

    return arr;
  },
  // 项目过滤
  filterProject(event: any) {
    let list = [] as any;
    this.data.projectList.forEach((item: any) => {
      if (item.text.toLowerCase().indexOf(event.detail.toLowerCase()) >= 0) {
        list.push(item);
      }
    });
    this.setData({
      filterProjectList: list,
      projectSearchVal: event.detail
    });
  },
  // 处理人过滤
  filterUser(event: any) {
    let list = [] as any;
    this.data.userList.forEach((item: any) => {
      if (item.text.toLowerCase().indexOf(event.detail.toLowerCase()) >= 0) {
        list.push(item);
      }
    });
    this.setData({
      filterUserList: list,
      userSearchVal: event.detail
    });
  },
  // 回访人过滤
  filterReviewUser(event: any) {
    let list = [] as any;
    this.data.reviewUserList.forEach((item: any) => {
      if (item.text.toLowerCase().indexOf(event.detail.toLowerCase()) >= 0) {
        list.push(item);
      }
    });
    this.setData({
      filterReviewUserList: list,
      reviewUserSearchVal: event.detail
    });
  },
  // 回访模板过滤
  filterCustomerFollowTemplate(event: any) {
    let list = [] as any;
    this.data.customerFollowTemplateList.forEach((item: any) => {
      if (item.text.toLowerCase().indexOf(event.detail.toLowerCase()) >= 0) {
        list.push(item);
      }
    });
    this.setData({
      filterCustomerFollowTemplateList: list,
      customerFollowTemplateSearchVal: event.detail
    });
  },
  //下拉框切换是否展示
  pickerChange(event: any) {
    let { fieldname, index, idx } = event.currentTarget.dataset;
    let data: any = { ...this.data };
    data.showList[fieldname] = true;
    // 选中的是满意度
    if (fieldname == 'pleasedStatusShow') {
      let currentIndex = {
        index,
        idx
      };
      data.currentIndex = currentIndex;
    }
    this.setData(data);
  },
  // 关闭下拉选择/日期选择
  hidePicker() {
    let keys = Object.keys(this.data.showList);
    let list = this.data.showList as any;
    keys.forEach(item => {
      list[item] = false;
    });
    this.setData({
      showList: list
    });
  },
  // input输入
  inputChange(event: any) {
    let { fieldname, type, require, texttype } = event.currentTarget.dataset;
    let data: any = this.data;
    let result = event.detail.value;
    let regex = /[!@#$%^&*?><|\\\\]/;
    let phoneRegex = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;
    let spaceRegex = new RegExp(/\s+/g);
    let message = '';
    // 有填写内容，校验特殊字符
    if (result && regex.test(result)) {
      message = '不支持特殊字符';
    } else if (spaceRegex.test(result)) message = '不支持含有空格';
    else if (texttype != 'textarea' && result.length > 32)
      message = '输入长度不得超过32个字符';
    else if (texttype == 'textarea' && result.length > 500)
      message = '输入长度不得超过500个字符';
    else if (result && fieldname == 'phone' && !phoneRegex.test(result)) {
      message = '联系电话格式错误';
    }
    // 没有填写内容且不为必填
    else if (!result && require != 'norequire') {
      message = '请填写必填项';
    } else if (result) {
      message = '';
    }
    if (type) {
      data.params[type][fieldname] = result;
    } else {
      data.params[fieldname] = result;
    }
    if (type) {
      if (
        Object.prototype.hasOwnProperty.call(
          data.requireObj[type + 'Info'],
          fieldname
        )
      )
        data.requireObj[type + 'Info'][fieldname] = message;
      if (
        Object.prototype.hasOwnProperty.call(
          data.validateObj[type + 'Info'],
          fieldname
        )
      )
        data.validateObj[type + 'Info'][fieldname] = message;
    } else {
      if (
        Object.prototype.hasOwnProperty.call(
          data.requireObj.baseInfo,
          fieldname
        )
      )
        data.requireObj.baseInfo[fieldname] = message;
      if (
        Object.prototype.hasOwnProperty.call(
          data.validateObj.baseInfo,
          fieldname
        )
      )
        data.validateObj.baseInfo[fieldname] = message;
    }
    this.setData(data);
  },
  // 模板备注输入
  partListRemarkChange(event: any) {
    let { fieldname, index, idx } = event.currentTarget.dataset;
    // let idx = event.currentTarget.dataset.index
    let data: any = this.data;
    data[fieldname][index][idx].remark = event.detail.value;
    let message = '';
    if (event.detail.value) {
      let regex = /[!@#$%^&*?><|\\\\]/;
      let spaceRegex = new RegExp(/\s+/g);
      if (regex.test(event.detail.value)) message = '不支持特殊字符';
      else if (spaceRegex.test(event.detail.value)) message = '不支持含有空格';
      else if (event.detail.value.length > 200)
        message = '输入长度不得超过200个字符';
    } else message = '';
    if (fieldname == 'customerFollowTemplatePartList')
      data.validateObj.baseInfo.partList[index][idx].remark = message;
    if (fieldname == 'inspectionTemplatePartList')
      data.validateObj.inspectionTaskInfo.partList[index][idx].remark = message;
    this.setData(data);
  },
  // 文件上传
  fileAfterRead(event: any) {
    const file = event.detail;
    let index: any = event.detail.index;
    let { list, type } = event.currentTarget.dataset;
    let data: any = this.data;
    let option = {
      name: 'file',
      filePath: event.detail.file.url
    };
    data[list][index] = {
      status: 'uploading',
      message: '上传中'
    };
    data.uploading = true;
    this.setData(data);
    upload('api/customerFollow/upload', option)
      .then((res: any) => {
        let tempData = JSON.parse(res.data);
        if (!tempData.success) {
          wx.showToast({
            title: tempData.message,
            icon: 'none'
          });
          data[list][index] = {
            status: 'failed',
            message: '上传失败'
          };
          data.uploading = false;
          this.setData(data);
          return;
        }
        data[list][index] = {
          ...file,
          url: tempData.message,
          status: 'done',
          message: '上传完成'
        };
        console.log(data[list]);

        data.uploading = false;
        // 地址拼接
        let fileUrl;
        if (type) {
          fileUrl = data.params[type].fileUrl
            ? data.params[type].fileUrl + ',' + tempData.message
            : tempData.message;
          data.params[type].fileUrl = fileUrl;
        } else {
          fileUrl = data.params.fileUrl
            ? data.params.fileUrl + ',' + tempData.message
            : tempData.message;
          data.params.fileUrl = fileUrl;
        }
        this.setData(data);
      })
      .catch(err => {
        data.uploading = false;
      });
  },
  // 删除文件
  deleteFile(event: any) {
    let { list, type } = event.currentTarget.dataset;
    let data: any = this.data;
    let index = event.detail.index;
    data[list].splice(index, 1);
    if (data.params[type]?.fileUrl) {
      data.params[type].fileUrl = data[list]
        .map((item: any) => {
          return item.url;
        })
        .join(',');
    } else if (data.params.fileUrl) {
      data.params.fileUrl = data[list]
        .map((item: any) => {
          return item.url;
        })
        .join(',');
    }
    this.setData(data);
  },
  // 校验
  validateFn() {
    let data: any = this.data;
    let result = true;
    // 校验基础信息和回访信息
    let baseInfoKeys = Object.keys(data.requireObj.baseInfo);
    baseInfoKeys.forEach((item: any) => {
      if (data.requireObj.baseInfo[item]) result = false;
      if (!data.params[item]) {
        data.requireObj.baseInfo[item] = '请填写必填项';
        result = false;
      }
    });
    // 校验车辆巡检
    if (data.contentItem.inspectionTask) {
      let inspectionTaskKeys = Object.keys(data.requireObj.inspectionTaskInfo);
      inspectionTaskKeys.forEach((item: any) => {
        // 没有填写异常处理
        if (
          !data.contentItem.handle &&
          (item == 'handlePlan' || item == 'handleType' || item == 'handleTime')
        )
          return;
        if (data.requireObj.inspectionTaskInfo[item]) result = false;
        if (!data.params.inspectionTask[item]) {
          data.requireObj.inspectionTaskInfo[item] = '请填写必填项';
          result = false;
          return;
        }
        // 处理方案
        if (data.contentItem.handle && item == 'handlePlan') {
          let regex = /[!@#$%^&*?><|\\\\]/;
          let spaceRegex = new RegExp(/\s+/g);
          let message = '';
          // 有填写内容，校验特殊字符
          if (result && regex.test(data.params.inspectionTask[item])) {
            message = '不支持特殊字符';
            result = false;
          } else if (spaceRegex.test(data.params.inspectionTask[item])) {
            message = '不支持含有空格';
            result = false;
          } else if (data.params.inspectionTask[item].length > 500) {
            message = '输入长度不得超过500个字符';
            result = false;
          }
          data.requireObj.inspectionTaskInfo[item] = message;
        }
      });
    }
    // 校验意见反馈
    if (data.contentItem.opinion) {
      let opinionKeys = Object.keys(data.requireObj.opinionInfo);
      opinionKeys.forEach((item: any) => {
        if (data.requireObj.opinionInfo[item]) result = false;
        if (!data.params.opinion[item]) {
          data.requireObj.opinionInfo[item] = '请填写必填项';
          result = false;
        }
      });
    }
    // 校验非必填特殊字符
    if (
      data.validateObj.baseInfo.remark ||
      data.validateObj.inspectionTaskInfo.remark ||
      data.validateObj.opinionInfo.remark
    )
      result = false;
    // 模板校验
    for (const item of data.validateObj.baseInfo.partList) {
      let res = item.some((el: any) => {
        return el.remark !== '';
      });
      if (res) {
        result = false;
        break;
      }
    }
    for (const item of data.validateObj.inspectionTaskInfo.partList) {
      let res = item.some((el: any) => {
        return el.remark !== '';
      });
      if (res) {
        result = false;
        break;
      }
    }
    // 车辆校验
    for (const item of data.validateObj.inspectionTaskInfo.vehicles) {
      if (item.remark != '') {
        result = false;
        break;
      }
    }
    this.setData(data);
    return result;
  },
  // 校验文件
  checkFile() {
    let { baseInfoFileList, inspectionTaskFileList, opinionFileList } =
      this.data;
    let result = true;
    if (
      baseInfoFileList &&
      baseInfoFileList.some((item: any) => {
        return item.status == 'failed';
      })
    )
      result = false;
    if (
      inspectionTaskFileList &&
      inspectionTaskFileList.some((item: any) => {
        return item.status == 'failed';
      })
    )
      result = false;
    if (
      opinionFileList &&
      opinionFileList.some((item: any) => {
        return item.status == 'failed';
      })
    )
      result = false;
    return result;
  },
  // 提交
  formSubmit() {
    // 防止重复提交
    if (this.data.isSubmit) return;
    // 校验
    if (!this.validateFn()) return;
    // 校验文件是否正在上传
    if (this.data.uploading) {
      wx.showToast({
        title: '文件上传中，请稍后',
        icon: 'none'
      });
      return;
    }
    // 校验是否有错误文件
    if (!this.checkFile()) {
      wx.showToast({
        title: '请删除错误文件',
        icon: 'none'
      });
      return;
    }
    let params: any = JSON.parse(JSON.stringify(this.data.params));
    // 回访模板
    params.partList = [].concat(...this.data.customerFollowTemplatePartList);
    // 有勾选车辆巡检
    if (this.data.contentItem.inspectionTask) {
      // 巡检模板
      params.inspectionTask.partList = [].concat(
        ...this.data.inspectionTemplatePartList
      );
      // 车辆信息
      params.inspectionTask.vehicles = this.data.vehicleList;
      params.inspectionTask.attachment = params.inspectionTask.fileUrl;
      delete params.inspectionTask.fileUrl;
    } else {
      delete params.inspectionTask;
    }
    // 没有有勾选意见反馈
    if (!this.data.contentItem.opinion) {
      delete params.opinion;
    }
    // 没有填写异常处理
    if (!this.data.contentItem.handle && params.inspectionTask) {
      params.inspectionTask.handlePlan = '';
      params.inspectionTask.handleType = '';
      params.inspectionTask.handleTime = '';
    }
    wx.showLoading({
      title: '加载中'
    });
    this.setData({
      isSubmit: true
    });
    let url, action;
    // 编辑
    if (this.data.isEdit) {
      url = 'api/customerFollow/edit';
      action = putAction;
    }
    // 新增
    else {
      url = 'api/customerFollow/add';
      action = postAction;
      delete params.id;
    }
    action(url, params)
      .then((res: any) => {
        wx.hideLoading();
        if (res.code == 200) {
          wx.showToast({
            title: '提交成功',
            icon: 'success'
          });
          if (this.data.isEdit) {
            setTimeout(() => {
              wx.navigateTo({
                url: '../../../pages/backlog/backlogFeedback/backlogFeedback',
                fail: e => {
                  console.log(e);
                }
              });
              this.setData({
                isSubmit: false
              });
              wx.hideToast();
            }, 1000);
          } else {
            setTimeout(() => {
              wx.navigateBack({
                delta: 1
              });
              this.setData({
                isSubmit: false
              });
              wx.hideToast();
            }, 1000);
          }
        } else {
          wx.showToast({
            title: res.message,
            icon: 'none'
          });
          this.setData({
            isSubmit: false
          });
        }
      })
      .catch(err => {
        console.log(err);
        this.setData({
          isSubmit: false
        });
      });
  },
  // 获取项目
  getProjectOptions() {
    getAction('api/projects/list').then((res: any) => {
      if (res.code == 200) {
        let arr = [] as any;
        res.result.forEach((item: any, index: number) => {
          arr.push({
            text: item.projectName,
            value: item.id
          });
        });
        this.setData({
          projectList: arr,
          filterProjectList: arr
        });
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none'
        });
      }
    });
  },
  // 获取用户
  getUser() {
    getAction('api/sys/user/list?pageSize=-1&pageNo=1').then((res: any) => {
      if (res.success) {
        let arr = [] as any;
        res.result.records.forEach((item: any, index: number) => {
          arr.push({
            text: item.realname,
            value: item.id
          });
        });
        this.setData({
          userList: arr,
          reviewUserList: arr,
          filterUserList: arr,
          filterReviewUserList: arr
        });
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none'
        });
      }
    });
  },
  // 获取客户回访模板
  getCustomerFollowTemplate() {
    getAction('api/customerFollowTemplate/list?pageNo=1&pageSize=-1').then(
      (res: any) => {
        if (res.success) {
          let arr = [] as any;
          res.result.records.forEach((item: any, index: number) => {
            arr.push({
              text: item.name,
              value: item.id,
              partList: item.partList
            });
          });
          this.setData({
            customerFollowTemplateList: arr,
            filterCustomerFollowTemplateList: arr
          });
        } else {
          wx.showToast({
            title: res.message,
            icon: 'none'
          });
        }
      }
    );
  },
  // 获取巡检模板模板
  getInspectionTemplate() {
    getAction('api/inspectionTemplate/list?pageNo=1&pageSize=-1').then(
      (res: any) => {
        if (res.success) {
          let arr = [] as any;
          res.result.records.forEach((item: any, index: number) => {
            arr.push({
              text: item.name,
              value: item.id,
              partList: item.projectList
            });
          });
          this.setData({
            inspectionTemplateList: arr,
            filterInspectionTemplateList: arr
          });
        } else {
          wx.showToast({
            title: res.message,
            icon: 'none'
          });
        }
      }
    );
  },
  // 获取车辆数据
  getVehicle(projectId: any) {
    getAction(
      `api/vehicle/listByProjectId?pageSize=-1&pageNo=1&projectId=${projectId}`
    ).then((res: any) => {
      if (res.success) {
        let arr: any = [];
        let validate: any = [];
        let data: any = this.data;
        res.result.forEach((item: any) => {
          arr.push({
            vehicleId: item.id,
            plateNumber: item.plateNumber,
            isNormal: '1',
            abnormalMsg: ''
          });
          validate.push({ remark: '' });
        });
        data.vehicleList = JSON.parse(JSON.stringify(arr));
        data.originVehicleList = JSON.parse(JSON.stringify(arr));
        data.validateObj.inspectionTaskInfo.vehicles = validate;
        this.setData({
          vehicleList: arr,
          originVehicleList: JSON.parse(JSON.stringify(arr))
        });
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none'
        });
      }
    });
  },
  // 获取字典
  getDict() {
    getAction('api/sys/dict/queryAllDictItems').then((res: any) => {
      let result: any = res.result;
      this.setData({
        reviewTypeList: result.review_type, // 回访方式
        resultStatusList: result.result_status, // 回访结果
        opinionStatusList: result.opinion_status, // 回访结果(编辑状态用)
        inspectionResultList: result.inspection_result, // 巡检结果
        opinionTypeList: result.opinion_type // 意见分类
      });
    });
  },
  getInf() {
    let info = wx.getStorageSync('customerFollowData');
    let data: any = this.data;
    wx.removeStorageSync('customerFollowData');
    if (info) {
      getAction(`api/vehicles/backlog/getFollowInfoById?id=${info}`).then(
        (res: any) => {
          let result: any = res.result;
          // 编辑模式
          data.isEdit = true;
          // 勾选
          if (result.inspectionTask) data.contentItem.inspectionTask = true;
          if (result.opinion) data.contentItem.opinion = true;
          // 基本信息和回访信息
          for (const key in data.params) {
            if (
              key != 'inspectionTask' &&
              key != 'opinion' &&
              key != 'partList'
            ) {
              data.params[key] = result[key];
            }
          }
          // 翻译
          data.dictTextList.projectId_dictText = result.projectId_dictText;
          data.dictTextList.reviewType_dictText = result.reviewType_dictText;
          data.dictTextList.reviewUserId_dictText =
            result.reviewUserId_dictText;
          data.dictTextList.resultStatus_dictText =
            result.resultStatus_dictText;
          data.dictTextList.customerFollowTemplate_dictText =
            result.templateId_dictText;
          // 如果回访结果是未开始，清空
          if (result.resultStatus === '0') {
            data.params.resultStatus = '';
            data.dictTextList.resultStatus_dictText = '';
          }
          // 回访模板
          data.customerFollowTemplatePartList = this.changeTemplate(
            result.partList,
            'categoryName',
            'followName',
            'pleasedStatus'
          );
          // 回访模板校验
          data.validateObj.baseInfo.partList = [];
          data.customerFollowTemplatePartList.forEach((item: any) => {
            let arr: any = [];
            for (let i = 0; i < item.length; i++) {
              arr.push({ remark: '' });
            }
            data.validateObj.baseInfo.partList.push(arr);
          });
          // 回访附件
          data.baseInfoFileList = this.changeUrl(result.fileUrl);
          // 车辆巡检
          if (result.inspectionTask) {
            for (const key in data.params.inspectionTask) {
              data.params.inspectionTask[key] = result.inspectionTask[key];
            }
            // 巡检附件
            data.inspectionTaskFileList = this.changeUrl(
              result.inspectionTask.attachment
            );
            // 翻译
            data.dictTextList.inspectionTemplate_dictText =
              result.inspectionTask.inspectionTemplateId_dictText;
            data.dictTextList.inspectionResult_dictText =
              result.inspectionTask.inspectionResult_dictText;
            // 车辆数据
            data.vehicleList = result.inspectionTask.vehicleList;
            // 巡检模板
            data.inspectionTemplatePartList = this.changeTemplate(
              result.inspectionTask.partList,
              'name',
              'content',
              'normal'
            );
            // 异常处理
            if (result.inspectionTask.inspectionResult === '0')
              data.contentItem.handle = true;
            data.dictTextList.handleType_dictText =
              result.inspectionTask.handleType_dictText;
          }
          // 意见反馈
          if (result.opinion) {
            for (const key in data.params.opinion) {
              data.params.opinion[key] = result.opinion[key];
            }
            // 反馈附件
            data.opinionFileList = this.changeUrl(result.opinion.fileUrl);
            // 翻译
            data.dictTextList.opinionType_dictText =
              result.opinion.opinionType_dictText;
            data.dictTextList.handleId_dictText =
              result.opinion.handleId_dictText;
          }
          this.setData(data);
        }
      );
    }
  },
  // 附件翻译
  changeUrl(data: any) {
    if (!data) return;
    let urls = data.split(',');
    let result = [] as any;
    urls.forEach((item: any, index: number) => {
      result.push({
        index: index,
        message: '上传完成',
        name: '',
        status: 'done',
        url: item,
        file: {
          url: item
        }
      });
    });
    return result;
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.getProjectOptions();
    this.getUser();
    this.getCustomerFollowTemplate();
    this.getInspectionTemplate();
    this.getDict();
    this.getInf();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {}
});
