import HTTP from "../../../../../requestFn/Api"
import {
  timestamp,
  formatArr,
  formatTimeTwo
} from "../../../utils/util"
const app = getApp();
const {
  baseURL
} = app.globalData;
Page({
  data: {
    house_list: [],
    contacter: '',
    phone: '',
    house_pic: [],
    cert_pic: [],
    pics: [{
        name: "房屋照片",
        uploadFiles: []
      },
      {
        name: "房屋证件",
        uploadFiles: []
      }
    ],
    gridConfig: {
      width: 218,
      height: 218,
      column: 3,
    },
    imageProps: {
      mode: 'aspectFit',
    },
    price_list: [{
      label: "租金",
      name: "rent_price",
      value: '',
    }, {
      label: "押金",
      name: "desposit",
      value: '',
    }, ],
    select_list: [{
        label: "出租方式",
        range: [{
            name: "整租",
            value: 1
          },
          {
            name: "合租",
            value: 2
          }, {
            name: "转租",
            value: 3
          }
        ],
        range_key: "name",
        value: '',
        name: 'type'
      },
      {
        label: "房屋",
        range: [],
        range_key: "house_name",
        value: '',
        name: "house_id",
      },
      {
        label: "装修情况",
        range: [{
            name: "精装",
            value: 1
          },
          {
            name: "简装",
            value: 2
          },
          {
            name: "清水",
            value: 3
          }
        ],
        range_key: "name",
        name: "decorating",
        value: ''
      },
      {
        label: '朝向',
        range: [{
            name: "东",
            value: 1
          },
          {
            name: "南",
            value: 1
          },
          {
            name: "西",
            value: 1
          },
          {
            name: "北",
            value: 1
          },
        ],
        range_key: "name",
        name: "direction",
        value: ''
      },
      {
        label: "房间类型",
        range: [{
            name: '全部',
            value: 1
          },
          {
            name: '主卧',
            value: 2
          },
          {
            name: '次卧',
            value: 3
          },
        ],
        range_key: "name",
        name: "room_type",
        value: ''
      },
      {
        label: "付款方式",
        range: [{
            name: "月付",
            value: 1
          },
          {
            name: "季付",
            value: 2
          },
          {
            name: "半年付",
            value: 3
          },
          {
            name: "年付",
            value: 4
          },
        ],
        range_key: "name",
        name: "pay_time_type",
        value: ''
      },
      {
        label: "卫生间",
        range: [{
            name: '一卫',
            value: 1
          },
          {
            name: '二卫',
            value: 2
          },
          {
            name: '三卫',
            value: 3
          },
        ],
        range_key: "name",
        name: "wc_count",
        value: ''
      },
      {
        label: "入住时间",
        value: '',
      }
    ],
    conf_list: [{
        label: "基础设施",
        name: "base_conf_list",
        list: [{
            name: "床",
            checked: false,
            value: 1
          },
          {
            name: "天然气",
            checked: false,
            value: 2
          },
          {
            name: "暖气",
            checked: false,
            value: 3
          },
          {
            name: "宽带",
            checked: false,
            value: 4
          },
          {
            name: "冰箱",
            checked: false,
            value: 5
          },
          {
            name: "衣柜",
            checked: false,
            value: 6
          },
          {
            name: "沙发",
            checked: false,
            value: 7
          },
          {
            name: "空调",
            checked: false,
            value: 8
          },
          {
            name: "电视机",
            checked: false,
            value: 9
          },
          {
            name: "热水器",
            checked: false,
            value: 10
          },
          {
            name: "洗衣机",
            checked: false,
            value: 11
          },
        ],
      },
      {
        label: "房源特色",
        name: "special_list",
        list: [{
            name: "智能门锁",
            checked: false,
            value: 1
          },
          {
            name: "WIFI",
            checked: false,
            value: 2
          },
          {
            name: "近地铁",
            checked: false,
            value: 3
          },
          {
            name: "停车位",
            checked: false,
            value: 4
          },
          {
            name: "独卫",
            checked: false,
            value: 5
          },
          {
            name: "私人阳台",
            checked: false,
            value: 6
          },
          {
            name: "首次出租",
            checked: false,
            value: 7
          },
        ]
      }
    ],
    room_area_value: '',
    base_value: [],
    special_value: [],
    house_info: null,
    desc: '',
    option: '立即提交',
    items: [{
      name: '1',
      value: '我已阅读并同意'
    }, ],
  },
  onLoad(options) {
    const that = this;
    this.getMyHouse();
    const eventChannel = that.getOpenerEventChannel();
    eventChannel.on('acceptDataFromOpenerPage', function (data) {
      that.setData({
        house_info: data
      })
    })
  },
  async getMyHouse() {
    const that = this;
    const {
      list
    } = await HTTP.GetuserHouse();
    const range = list.map(item=>{
      return {...item,house_name:`${item.house_name}(${item.garden_name})`}
    })
    this.setData({ 
      house_list: list,
      ['select_list[1].range']: range
    });
    const {
      house_info
    } = this.data;
    if (house_info) {
      const {
        house_info,
        house_list
      } = that.data;
      let house_index;
      house_list.map((item, index) => {
        if (item.house_id == house_info.house_id) {
          house_index = index
        }
      })
      const house_pic = house_info.house_pic.map(item => {
        return {
          url: item
        }
      })
      const cert_pic = house_info.cert_pic.map(item => {
        return {
          url: item
        }
      })
      that.setData({
        ['select_list[0].value']: house_info.rent_type - 1 + '',
        ['select_list[1].value']: house_index+'',
        ['select_list[2].value']: house_info.decorating - 1 + '',
        ['select_list[3].value']: house_info.direction - 1 + '',
        ['select_list[4].value']: house_info.room_type - 1 + '',
        ['select_list[5].value']: house_info.pay_time_type - 1 + '',
        ['select_list[6].value']: house_info.wc_count - 1 + '',
        ['select_list[7].value']: house_info.in_time==0?0:formatTimeTwo(house_info.in_time, 'Y-M-D'),
        ['price_list[0].value']: house_info.rent_price / 100,
        ['price_list[1].value']: house_info.desposit / 100,
        room_area_value: house_info.room_area,
        contacter: house_info.contacter,
        phone: house_info.contact_phone,
        desc: house_info.desc,
        ['pics[0].uploadFiles']: house_pic,
        ['pics[1].uploadFiles']: cert_pic,
        house_pic: house_info.house_pic,
        cert_pic: house_info.cert_pic,
        option: '修改信息'
      })
      formatArr(house_info.base_conf).map(item => {
        that.setData({
          [`conf_list[0].list[${item-1}].checked`]: true
        })
      })
      formatArr(house_info.special_conf).map(item => {
        that.setData({
          [`conf_list[1].list[${item-1}].checked`]: true
        })
      })
    }
  },
  async submit(e) {
    const {
      type,
      house_id,
      decorating,
      direction,
      room_type,
      pay_time_type,
      wc_count,
      time,
      rent_price,
      desposit,
      room_area,
      contacter,
      contact_phone,
      base_conf_list,
      special_list,
      desc,
      notice
    } = e.detail.value;
    const {
      house_pic,
      cert_pic,
      house_list,
      select_list,
      option,
      house_info
    } = this.data;
    const base_conf = this.getConf(base_conf_list);
    const special_conf = this.getConf(special_list);
    if (this.checkSelect(type, '出租方式') &&
      this.checkSelect(house_id, '房屋') &&
      this.checkSelect(decorating, '装修情况') &&
      this.checkSelect(direction, '朝向') &&
      this.checkSelect(room_type, '房间类型') &&
      this.checkSelect(pay_time_type, '付款方式') &&
      this.checkSelect(wc_count, '卫生间') &&
      this.checkSelect(rent_price, '租金', 'input') &&
      this.checkNum(rent_price, '租金') &&
      this.checkSelect(desposit, '压金', 'input') &&
      this.checkNum(desposit, '压金') &&
      this.checkSelect(room_area, '房屋面积', 'input') &&
      this.checkNum(room_area, '房屋面积') &&
      this.checkSelect(contacter, '联系人', 'input') &&
      this.checkSelect(contact_phone, '联系方式', 'input') &&
      this.checkPhone(contact_phone) &&
      this.checkArr(base_conf_list, '基础设施') &&
      this.checkArr(special_list, '房源特色') &&
      this.checkArr(house_pic, '房屋照片', 'pics') &&
      this.checkArr(cert_pic, '房屋证件', 'pics') &&
      this.checkSelect(desc, '房源简介', 'input') &&
      this.checkNotice(notice)
    ) {
      const res = await HTTP.RentHouse({
        method: option == '立即提交' ? 'post' : 'put',
        id: option == '立即提交' ? '' : house_info.id,
        rent_type: select_list[0].range[type].value,
        garden_id: house_list[house_id].garden_id,
        house_id: house_list[house_id].house_id,
        household_uid: house_list[house_id].id,
        decorating: select_list[2].range[decorating].value,
        direction: select_list[3].range[direction].value,
        room_type: select_list[4].range[room_type].value,
        pay_time_type: select_list[5].range[pay_time_type].value,
        wc_count: select_list[6].range[wc_count].value,
        in_time: time == '' ? 0 : timestamp(time),
        rent_price: rent_price * 100 - 0,
        desposit: desposit * 100 - 0,
        room_area: room_area - 0,
        contacter,
        contact_phone,
        house_pic,
        cert_pic,
        desc,
        base_conf,
        special_conf
      })
      if (res.code == 0) {
        wx.showToast({
          title: '提交成功',
          icon: "success",
          success() {
            setTimeout(() => {
              wx.navigateBack()
            }, 1000)
          }
        })
      }
    }
  },
  bindSelectChange(e) {
    const {
      index
    } = e.currentTarget.dataset;
    this.setData({
      [`select_list[${index}].value`]: e.detail.value,
    })
  },
  getContacterValue(e) {
    this.setData({
      contacter: e.detail.value
    })
  },
  getPhoneValue(e) {
    this.setData({
      phone: e.detail.value
    })
  },
  clearContacterValue() {
    this.setData({
      contacter: ''
    })
  },
  clearPhoneValue() {
    this.setData({
      phone: ''
    })
  },
  handleRemove(e) {
    const num = e.currentTarget.dataset.index;
    const {
      index
    } = e.detail;
    const {
      uploadFiles
    } = this.data.pics[num];
    const {
      house_pic,
      cert_pic
    } = this.data;
    uploadFiles.splice(index, 1);
    if (num == 0) {
      house_pic.splice(index, 1);
    } else {
      cert_pic.splice(index, 1);
    }
    this.setData({
      [`pics[${num}].uploadFiles`]: uploadFiles,
      house_pic,
      cert_pic
    });
  },
  handleSuccess(e) {
    const {
      index
    } = e.currentTarget.dataset;
    const that = this;
    const {
      files
    } = e.detail;
    const userInfo = wx.getStorageSync('userInfo');
    const result = [];
    files.map(item => {
      wx.uploadFile({
        filePath: item.url,
        name: 'file',
        url: baseURL + '/upload',
        header: {
          "token": userInfo.token
        },
        success(res) {
          result.push(JSON.parse(res.data).data)
          if (index == 0) {
            that.setData({
              house_pic: result
            })
          } else {
            that.setData({
              cert_pic: result
            })
          }
        },
        fail(res) {
          console.log(res);
        }
      })
    })
    this.setData({
      [`pics[${index}].uploadFiles`]: files,
    });
  },
  checkSelect(value, title, type = 'select') {
    let flag = false;
    if (value == '') {
      wx.showToast({
        title: `${type}` == 'select' ? `请选择${title}` : `请输入${title}`,
        duration: 2000,
        icon: "error",
      });
    } else {
      flag = true;
    }
    return flag
  },
  checkNum(value, title) {
    let flag = false;
    if (isNaN(Number(value))) {
      wx.showToast({
        title: `${title}一栏请输入数字`,
        duration: 2000,
        icon: 'none'
      });
    } else {
      flag = true;
    }
    return flag
  },
  checkArr(val, title, type = 'conf') {
    let flag = false;
    if (val.length == 0) {
      wx.showToast({
        title: `${type}` == 'conf' ? `请选择${title}` : `请上传${title}`,
        duration: 2000,
        icon: "error",
      });
    } else {
      flag = true;
    }
    return flag
  },
  checkNotice(val) {
    let flag = false;
    if (val.length == 0) {
      wx.showToast({
        title: '请阅读并同意协议',
        duration: 2000,
        icon: "none",
      });
    } else {
      flag = true;
    }
    return flag
  },
  checkPhone(val) {
    let flag = false;
    if (!/^1[345789]\d{9}$/.test(val)) {
      wx.showToast({
        title: `手机格式有误`,
        duration: 2000,
        icon: 'error'
      });
    } else {
      flag = true;
    }
    return flag
  },
  getConf(val) {
    let value = 0;
    val.forEach(n => {
      value = value | (1 << n)
    })
    return value
  },
  alertNotice() {
    wx.navigateTo({
      url: '../notice/notice',
    })
  },
  housedown(e) {
    const that = this;
    const {
      garden_id,
      id
    } = that.data.house_info;
    console.log(garden_id, id);
    wx.showModal({
      title: "提示",
      content: "是否下架该房源",
      success: function (res) {
        if (res.confirm) {
          that.deleteHTTP(garden_id, id);
        } else if (res.cancel) {}
      }
    })
  },
  async deleteHTTP(garden_id, id) {
    const res = await HTTP.HouseDown({
      garden_id,
      id
    });
    if (res.code == 0) {
      wx.showToast({
        title: '下架成功',
        icon: "success",
        success() {
          setTimeout(() => {
            wx.navigateBack({
              delta: 1
            })
          }, 500)
        }
      })
    }
  }
})