import Dialog from '@vant/weapp/dialog/dialog';
import { getAction, upload, postAction } from '../../../api/base';
const dayjs = require('dayjs');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    costList: [], // 车型数据
    filterCostList: [], // 车型过滤
    costListVal: '', // 车型查询
    currentIndex: '', // 当前点击车型的序号
    isSubmit: false, // 是否提交
    // 展开/收起
    showBox: {
      base: true,
      vehicleList: true
    },
    // 下拉选择/日期弹窗展示
    showList: {
      yearLimitShow: false,
      costListShow: false
    },
    // 提交数据
    params: {
      projectId: '', //项目
      yearLimit: 8, //年限
      financingRatio: 0, //融资比例
      financingRate: 0, //融资利率
      overheadSharing: 0, //管理费用分担
      vehicleCostList: [] // 车型信息
    },
    // 年限下拉
    yearLimitList: [
      { value: 1, text: '1年' },
      { value: 2, text: '2年' },
      { value: 3, text: '3年' },
      { value: 4, text: '4年' },
      { value: 5, text: '5年' },
      { value: 6, text: '6年' },
      { value: 7, text: '7年' },
      { value: 8, text: '8年' }
    ],
    // 翻译回显
    dictTextList: {
      yearLimit_dictText: '8年' // 租赁年限
    },
    // 基础信息校验
    requireObj: {
      projectId: '', //项目
      financingRatio: '', //融资比例
      financingRate: '', //融资利率
      overheadSharing: '' //管理费用分担
    },
    // 车型信息校验
    validateObj: {
      vehicleCostList: [],
      obj: {
        unitPrice: '', //单价
        purchaseTax: '', //上牌费用/购置税
        insurance: '', //保险
        repair: '', //维修及易损件
        upkeep: '', //保养
        annualAudit: '', //年审
        quantity: '', //数量
        salvageValue: '', //残值
        oneYear: '',
        twoYear: '',
        threeYear: '',
        fourYear: '',
        fiveYear: '',
        sixYear: '',
        sevenYear: '',
        eightYear: '',
        vehicleType: '' // 车型
      }
    },

    // 车型信息收起
    vehicleCostListShow: [],
    // 车型信息
    vehicleTypeInfo: [
      { label: '单价', prop: 'unitPrice', append: '万元' },
      { label: '上牌/购置税', prop: 'purchaseTax', append: '万元' },
      { label: '保险(万元/台/年)', prop: 'insurance', append: '万元' },
      { label: '维修及易损件(万元)', prop: 'repair', append: '万元' },
      { label: '保养(万元)', prop: 'upkeep', append: '万元' },
      { label: '年审(万元)', prop: 'annualAudit', append: '万元' }
    ],
    // 年收益
    yearList: [
      { label: '第一年', prop: 'oneYear', append: '万元', value: 1 },
      { label: '第二年', prop: 'twoYear', append: '万元', value: 2 },
      { label: '第三年', prop: 'threeYear', append: '万元', value: 3 },
      { label: '第四年', prop: 'fourYear', append: '万元', value: 4 },
      { label: '第五年', prop: 'fiveYear', append: '万元', value: 5 },
      { label: '第六年', prop: 'sixYear', append: '万元', value: 6 },
      { label: '第七年', prop: 'sevenYear', append: '万元', value: 7 },
      { label: '第八年', prop: 'eightYear', append: '万元', value: 8 }
    ]
  },
  // 新增车型信息
  addCostList() {
    let data: any = { ...this.data };
    let params = {
      unitPrice: 0, //单价
      purchaseTax: 0, //上牌费用/购置税
      insurance: 0, //保险
      repair: 0, //维修及易损件
      upkeep: 0, //保养
      annualAudit: 0, //年审
      quantity: 0, //数量
      salvageValue: 0, //残值
      oneYear: 0,
      twoYear: 0,
      threeYear: 0,
      fourYear: 0,
      fiveYear: 0,
      sixYear: 0,
      sevenYear: 0,
      eightYear: 0,
      vehicleType_dictText: '', // 车型回显
      vehicleType: '' // 车型
    };
    data.params.vehicleCostList.push(JSON.parse(JSON.stringify(params)));
    data.validateObj.vehicleCostList.push(JSON.parse(JSON.stringify(params))); // 校验
    data.vehicleCostListShow.push(true); // 显隐
    this.setData(data);
  },
  deleteCostList(event: any) {
    let { index } = event.currentTarget.dataset;
    let data: any = { ...this.data };
    data.params.vehicleCostList.splice(index, 1);
    data.vehicleCostListShow.splice(index, 1); // 删除显隐
    this.setData(data);
  },
  // 展示和收起
  showBoxInf(event: any) {
    let data: any = { ...this.data };
    let { fieldname, index } = event.currentTarget.dataset;
    if (fieldname == 'vehicleCostList') {
      data.vehicleCostListShow[index] = !data.vehicleCostListShow[index];
    } else data.showBox[fieldname] = !data.showBox[fieldname];
    this.setData(data);
  },
  //下拉框切换是否展示
  pickerChange(event: any) {
    let { fieldname, index } = event.currentTarget.dataset;
    let data: any = { ...this.data };
    data.showList[fieldname] = true;
    data.currentIndex = index;
    this.setData(data);
  },
  // 下拉选择/日期确认
  pickerConfirm(event: any) {
    //下拉框点击确认
    let { fieldname, dicttext } = event.currentTarget.dataset;
    let detail = event.detail;
    let data: any = { ...this.data };
    if (fieldname == 'yearLimit') {
      data.params[fieldname] = detail.value.value;
      data.dictTextList[dicttext] = detail.value.text;
    } else if (fieldname == 'vehicleType') {
      // data.params.vehicleCostList[data.currentIndex].vehicleType = detail.value.value
      let keys = Object.keys(data.params.vehicleCostList[data.currentIndex]);
      keys.forEach((item: any) => {
        if (detail.value[item])
          data.params.vehicleCostList[data.currentIndex][item] =
            detail.value[item];
        else data.params.vehicleCostList[data.currentIndex][item] = 0;
      });
      data.params.vehicleCostList[data.currentIndex].vehicleType_dictText =
        detail.value.value;
      data.validateObj.vehicleCostList[data.currentIndex].vehicleType = '';
    }

    this.setData(data);
    this.hidePicker();
  },

  // 项目过滤
  filterCostList(event: any) {
    let list = [] as any;
    this.data.costList.forEach((item: any) => {
      if (item.text.toLowerCase().indexOf(event.detail.toLowerCase()) >= 0) {
        list.push(item);
      }
    });
    this.setData({
      filterCostList: list,
      costListVal: event.detail
    });
  },

  // 关闭下拉选择/日期选择
  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 } = event.currentTarget.dataset;
    let data: any = this.data;
    let result = event.detail.value;
    let regex = /[!@#$%^&*?><|\\\\]/;
    let spaceRegex = new RegExp(/\s+/g);
    let message = '';
    // 有填写内容，校验特殊字符
    if (result && regex.test(result)) {
      message = '不支持特殊字符';
    } else if (spaceRegex.test(result)) message = '不支持含有空格';
    // 没有填写内容且不为必填
    else if (!result && require != 'norequire') {
      message = '请填写必填项';
    } else if (result.length > 32) {
      message = '输入长度不得超过32个字符';
    } else if (result) {
      message = '';
    }
    if (require != 'norequire') {
      data.requireObj[fieldname] = message;
    }
    data.params[fieldname] = result;
    this.setData(data);
  },

  // 数字输入
  numberChange(event: any) {
    let { fieldname, type, require, index } = event.currentTarget.dataset;
    let data: any = this.data;
    let result = event.detail.value;
    let message = '';
    const moneyNumberExp: RegExp = /^\d{1,9}(\.\d{1,4})?$/; //金额限制整数部分不能大于9位 小数部分不能大于4位
    const rateNumberExp: RegExp = /^\d+(\.\d{1,2})?$/; //小数部分不能大于2位
    if (type == 'rate') {
      if (result != '') {
        data.params[fieldname] = Number(result);
        if (result > 100) message = '百分比不能大于100%';
        else if (result < 0) data.params[fieldname] = 0;
        else if (!rateNumberExp.test(event.detail.value))
          message = '小数部分不能大于2位';
      } else data.params[fieldname] = 0;
    } else if (type == 'money') {
      if (result != '') {
        data.params.vehicleCostList[index][fieldname] = Number(result);
        if (result < 0) data.params.vehicleCostList[index][fieldname] = 0;
        else if (!moneyNumberExp.test(event.detail.value))
          message = '金额限制整数部分不能大于9位，小数部分不能大于4位';
      } else data.params.vehicleCostList[index][fieldname] = 0;
    } else if (type == 'quantity') {
      if (result != '') {
        data.params.vehicleCostList[index][fieldname] = Number(result);
        if (result < 0) data.params.vehicleCostList[index][fieldname] = 0;
        else if (result > 100000) message = '数量不能大于100000';
      } else data.params.vehicleCostList[index][fieldname] = 0;
    }
    if (require != 'noRequire') {
      data.requireObj[fieldname] = message;
    } else {
      if (index !== undefined) {
        data.validateObj.vehicleCostList[index][fieldname] = message;
      }
    }

    this.setData(data);
  },
  // 数量加减
  plusAndsubtract(event: any) {
    let { type, index } = event.currentTarget.dataset;
    let data: any = this.data;
    let message = '';
    if (type == 'plus') data.params.vehicleCostList[index].quantity += 1;
    else if (type == 'subtract')
      data.params.vehicleCostList[index].quantity -= 1;
    if (data.params.vehicleCostList[index].quantity < 0)
      data.params.vehicleCostList[index].quantity = 0;
    else if (data.params.vehicleCostList[index].quantity > 100000)
      message = '数量不能大于100000';
    else if (data.params.vehicleCostList[index].quantity <= 100000)
      message = '';
    data.validateObj.vehicleCostList[index].quantity = message;
    this.setData(data);
  },
  // 校验
  validateFn() {
    let data: any = this.data;
    let result = true;
    // 基础信息校验
    let requireObjKeys = Object.keys(data.requireObj);
    requireObjKeys.forEach((item: any) => {
      if (data.params[item] === '') {
        data.requireObj[item] = '请填写必填项';
        result = false;
      }
    });
    // 车型信息校验
    let validateObjKeys = Object.keys(data.validateObj.obj);
    data.params.vehicleCostList.forEach((item: any, index: any) => {
      validateObjKeys.forEach((el: any) => {
        let message = '';
        const moneyNumberExp: RegExp = /^\d{1,9}(\.\d{1,4})?$/; //金额限制整数部分不能大于9位 小数部分不能大于4位
        if (el == 'vehicleType') {
          if (!item[el]) {
            message = '请填写必填项';
            result = false;
          }
        } else if (el == 'quantity') {
          if (item[el] > 100000) {
            message = '数量不能大于100000';
            result = false;
          }
        } else {
          if (!moneyNumberExp.test(item[el])) {
            message = '金额限制整数部分不能大于9位，小数部分不能大于4位';
            result = false;
          }
        }
        // item[el] = message
        data.validateObj.vehicleCostList[index][el] = message;
      });
    });
    this.setData(data);
    return result;
  },

  // 提交
  formSubmit() {
    let data: any = this.data;
    if (data.isSubmit) return;
    // if (data.params.vehicleCostList.length == 0 ? true : false) {
    //   wx.showToast({
    //     title: '请新增车型信息',
    //     icon: 'none'
    //   })
    //   return
    // }
    // 校验
    if (!this.validateFn()) return;
    // 如果有修改租赁年限，需要清空高于租赁年限的数据
    // 当前年限以上的数据归零
    data.params.vehicleCostList.forEach((item: any) => {
      data.yearList.forEach((el: any, index: number) => {
        if (data.yearLimitList[index].value > data.params.yearLimit)
          item[el.prop] = 0;
      });
    });
    // 校验是否有数量为0
    let result = data.params.vehicleCostList.some((item: any) => {
      return item.quantity === 0;
    });
    if (result) {
      Dialog.confirm({
        title: '提示',
        message: '有车型信息数据中的数量值为零，会影响测算结果，是否进行测算'
      })
        .then(() => {
          wx.showLoading({
            title: '加载中'
          });
          this.setData({
            isSubmit: true
          });
          this.submitFn(data);
        })
        .catch(() => {});
    } else {
      wx.showLoading({
        title: '加载中'
      });
      this.setData({
        isSubmit: true
      });
      this.submitFn(data);
    }
  },
  submitFn(data: any) {
    postAction('api/finance/calculate/calculate', data.params)
      .then((res: any) => {
        if (res.success) {
          wx.showToast({
            title: '测算成功',
            icon: 'none'
          });
          let data: any = this.data;
          data.params.calculateObject = res.result;
          wx.setStorageSync('costEstimationData', {
            info: data.params,
            type: 'add'
          });
          setTimeout(() => {
            wx.navigateTo({
              url: '../costEstimationDetail/costEstimationDetail',
              fail: e => {
                console.log(e);
              }
            });
            this.setData({
              isSubmit: false
            });
            wx.hideLoading();
          }, 1000);
        } else {
          wx.hideLoading();
          wx.showToast({
            title: res.message,
            icon: 'none'
          });
          this.setData({
            isSubmit: false
          });
        }
      })
      .catch(err => {
        console.log(err);
        this.setData({
          isSubmit: false
        });
        wx.hideLoading();
      });
  },
  // 获取车型数据
  getCostList() {
    getAction('api/finance/calculate/costList').then((res: any) => {
      let result: any = res.result;
      result.forEach((item: any) => {
        item.text = item.vehicleType;
        item.value = item.vehicleType;
      });
      this.setData({
        costList: result, // 车型数据
        filterCostList: result // 车型过滤
      });
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.getCostList();
  },

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

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

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

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

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

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

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