<template>
  <view class="body-background"></view>
  <u-navbar
      :title="title"
      :auto-back="true"
      left-icon-size="40rpx"
      :safe-area-inset-top="true"
      :placeholder="true"
      bgColor="#ffffff"
  ></u-navbar>
  <u-row :custom-style="{padding:'16rpx 26rpx 180rpx'}">
    <u-col :span="12" :custom-style="{
      backgroundColor:'#FFFFFF',
      borderRadius:'20rpx',
      padding:'40rpx 32rpx',
      minHeight:'1000rpx',
      position:'relative'
    }">
      <u-form
          errorType="toast"
          labelWidth="200"
          labelPosition="left"
          :model="model"
          :rules="rules"
          ref="orderForm"
      >
        <view class="form-title">
          租房详情
        </view>
        <u-form-item
            label="承租人"
            prop="order.name"
            borderBottom
            :custom-style="{padding:'34rpx 0',fontSize:'32rpx',color:'#020b18',fontWeight:'400',lineHeight:'50rpx'}"
        >
          <u-input
              inputAlign="left"
              disabledColor="#ffffff"
              placeholder="请输入"
              border="none"
              :custom-style="{paddingRight:'28rpx'}"
              v-model="model.order.name"
              :disabled="true"
          ></u-input>
        </u-form-item>
        <u-form-item
            label="身份证号"
            prop="order.id_card"
            borderBottom
            :custom-style="{padding:'34rpx 0',fontSize:'32rpx',color:'#020b18',fontWeight:'400',lineHeight:'50rpx'}"
        >
          <u-input
              inputAlign="left"
              disabledColor="#ffffff"
              placeholder="请输入"
              border="none"
              :custom-style="{paddingRight:'28rpx'}"
              v-model="model.order.id_card"
              :disabled="true"
          ></u-input>
        </u-form-item>
        <u-form-item
            label="联系方式"
            prop="order.phone"
            borderBottom
            :custom-style="{padding:'34rpx 0',fontSize:'32rpx',color:'#020b18',fontWeight:'400',lineHeight:'50rpx'}"
        >
          <u-input
              inputAlign="left"
              disabledColor="#ffffff"
              placeholder="请输入"
              border="none"
              :custom-style="{paddingRight:'28rpx'}"
              v-model="model.order.phone"
              :disabled="true"
          ></u-input>
        </u-form-item>
        <u-form-item
            label="银行卡号"
            prop="order.bank_card"
            borderBottom
            :custom-style="{padding:'34rpx 0',fontSize:'32rpx',color:'#020b18',fontWeight:'400',lineHeight:'50rpx'}"
        >
          <u-input
              inputAlign="left"
              disabledColor="#ffffff"
              placeholder="请输入"
              border="none"
              :custom-style="{paddingRight:'28rpx'}"
              v-model="model.order.bank_card"
              :disabled="type==='detail'"
          ></u-input>
        </u-form-item>
        <u-form-item
            label="开户行"
            prop="order.bank_name"
            borderBottom
            :custom-style="{padding:'34rpx 0',fontSize:'32rpx',color:'#020b18',fontWeight:'400',lineHeight:'50rpx'}"
        >
          <u-input
              inputAlign="left"
              disabledColor="#ffffff"
              placeholder="请输入"
              border="none"
              :custom-style="{paddingRight:'28rpx'}"
              v-model="model.order.bank_name"
              :disabled="type==='detail'"
          ></u-input>
        </u-form-item>
        <u-form-item
            label="租期"
            prop="order.month"
            borderBottom
            :custom-style="{padding:'34rpx 0',fontSize:'32rpx',color:'#020b18',fontWeight:'400',lineHeight:'50rpx'}"
        >
          <u-input
              inputAlign="left"
              disabledColor="#ffffff"
              placeholder="请输入"
              border="none"
              type="number"
              :custom-style="{paddingRight:'28rpx'}"
              v-model="model.order.month"
              :disabled="(type !== 'create' && type !== 'edit')"
          >
            <template #suffix>
              <u-text text="个月" color="#020B18" size="32"></u-text>
            </template>
          </u-input>
        </u-form-item>
        <u-form-item
            label="租金"
            prop="order.rent"
            borderBottom
            :custom-style="{padding:'34rpx 0',fontSize:'32rpx',color:'#020b18',fontWeight:'400',lineHeight:'50rpx'}"
        >
          <u-input
              inputAlign="left"
              disabledColor="#ffffff"
              placeholder="请输入"
              border="none"
              :custom-style="{paddingRight:'28rpx'}"
              v-model="model.order.rent"
              :disabled="(type !== 'create' && type !== 'edit')"
          >
            <template #suffix>
              <u-text text="元/月" color="#020B18" size="32"></u-text>
            </template>
          </u-input>
        </u-form-item>
        <u-form-item
            label="合同到期时间"
            prop="order.end_time"
            borderBottom
            :custom-style="{padding:'34rpx 0',fontSize:'32rpx',color:'#020b18',fontWeight:'400',lineHeight:'50rpx'}"
        >
          <u-text suffix-icon="arrow-right" icon-style="font-size:32rpx;" align="left" :text="model.order.end_time || '请选择'" color="#020B18" size="32" @click="type !== 'apply' && type !== 'detail'&&$refs.endTime.open()"></u-text>
        </u-form-item>
        <u-form-item
            label="暖新币数量"
            prop="order.number"
            borderBottom
            :custom-style="{padding:'34rpx 0',fontSize:'32rpx',color:'#020b18',fontWeight:'400',lineHeight:'50rpx'}"
        >
          <u-input
              inputAlign="left"
              type="number"
              disabledColor="#ffffff"
              placeholder="请输入"
              border="none"
              :custom-style="{paddingRight:'28rpx'}"
              v-model="model.order.number"
              :disabled="(type === 'detail')"
          >
          </u-input>
        </u-form-item>
        <u-form-item
            prop="order.payment_voucher"
            :custom-style="{padding:'0 0',fontSize:'32rpx',color:'#020b18',fontWeight:'400',lineHeight:'50rpx'}"
        >
          <view class="form-label">
            打款凭证
          </view>
          <u-upload
              width="160"
              height="160"
              :fileList="fileList1"
              name="1"
              multiple
              uploadIcon="plus"
              @afterRead="afterFileRead1"
              @delete="deleteFile1"
              :disabled="type === 'detail'"
              :deletable="(type !== 'detail')"
              :maxCount="((type === 'create' || type === 'edit'|| type === 'apply')?999:fileList1.length)"
          ></u-upload>
        </u-form-item>
        <u-form-item
            prop="order.lease_agreement"
            :custom-style="{padding:'0 0',fontSize:'32rpx',color:'#020b18',fontWeight:'400',lineHeight:'50rpx'}"
        >
          <view class="form-label no-top-pad">
            租赁协议
          </view>
          <view class="row">
            <view class="">
              <u-upload
                  width="160"
                  height="160"
                  :fileList="fileList2"
                  name="1"
                  multiple
                  uploadIcon="plus"
                  @afterRead="afterFileRead2"
                  @delete="deleteFile2"
                  :disabled="(type !== 'create' && type !== 'edit')"
                  :deletable="(type === 'create' || type === 'edit')"
                  :maxCount="((type === 'create' || type === 'edit')?999:fileList2.length)"
              ></u-upload>
            </view>
          </view>
        </u-form-item>
      </u-form>
    </u-col>
  </u-row>
  <view class="foot-button border-box" v-if="(type === 'create' || type === 'edit' || type === 'apply')">
    <u-button
        type="primary"
        text="我要兑换"
        shape="circle"
        :custom-style="{
              color:'#020B18',
              backgroundColor:'#FF9545',
              border:'none',
              fontSize:'36',
              fontWeight:'400',
              height:'80rpx'
            }"
        @click="submit"
    ></u-button>
  </view>
<!--  <u-modal :show="modalShow" content="您的资料还未完善,确认前往完善?" @confirm="navTo('/pages/User/edit')" @close="navTo('/pages/Index/edit')" @cancel="navTo('/pages/Index/edit')"></u-modal>-->
  <uv-datetime-picker
      :minDate="new Date().getTime()"
      mode="date"
      ref="endTime"
      @confirm="endTimeSelect"
  >

  </uv-datetime-picker>
</template>

<script>
import {
  imghost
} from '@/config/host.js'
import MzSubsection from '@/components/MzSubsection/Index.vue';
import api from '@/utils/functions.js';
import {houseOrderDetail, submitApplyHouseOrder, submitHouseOrder, userExtends} from "@/api/user";
import {feedback} from "@/api/feed";

export default {
  components: {
    MzSubsection
  },
  data() {
    return {
      fileList1:[],
      fileList2:[],
      type:'create',
      model: {
        order: {
          house_order_id:'',
          house_id: '',
          name: '',
          id_card: '',
          phone: '',
          month: '',
          rent: '',
          payment_voucher: '',
          lease_agreement: '',
          bank_name:'',
          bank_card:'',
          number:'',
          end_time:'',
        },
      },
      rules: {
        'order.name': {
          type: 'string',
          required: true,
          message: '请填写承租人',
          trigger: ['blur', 'change']
        },
        'order.id_card': {
          type: 'string',
          required: true,
          message: '请填写身份证号',
          trigger: ['blur', 'change']
        },
        'order.phone': {
          type: 'string',
          required: true,
          message: '请填写联系方式',
          trigger: ['blur', 'change']
        },
        'order.month': {
          type: 'number',
          required: true,
          message: '请填写租期',
          trigger: ['blur', 'change']
        },
        'order.rent': {
          required: true,
          message: '请填写租金',
          trigger: ['blur', 'change']
        },
        'order.payment_voucher': {
          type: 'array',
          required: true,
          message: '请上传打款凭证',
          trigger: ['blur', 'change']
        },
        'order.lease_agreement': {
          type: 'array',
          required: true,
          message: '请上传租赁协议',
          trigger: ['blur', 'change']
        },
        'order.bank_name': {
          type: 'string',
          required: true,
          message: '请填写开户行',
          trigger: ['blur', 'change']
        },
        'order.bank_card': {
          type: 'string',
          required: true,
          message: '请填写银行卡号',
          trigger: ['blur', 'change']
        },
        'order.end_time': {
          type: 'string',
          required: true,
          message: '请选择合同到期时间',
          trigger: ['blur', 'change']
        },
        'order.number': {
          type: 'number',
          required: true,
          message: '请填写暖新币数量',
          trigger: ['blur', 'change']
        },
      },
      title: '租房详情',
      loading: true,
      size: {
        height: 500,
      }
    }
  },
  onLoad(option) {
      this.model.order.house_order_id = option.house_order_id?option.house_order_id:'';
      this.model.order.house_id  = option.id?option.id:'';
      this.model.order.rent = option.rent?parseFloat(option.rent)+'':'';
      this.type = option.type?option.type:'create';
  },
  onReady() {
    let that = this;
    let height = api.wxSystemInfo().system.windowHeight
    let headerHeight = uni.$u.getPx(44) + uni.$u.sys().statusBarHeight

    let info = uni.createSelectorQuery().in(this).select('.foot-button');
    info.boundingClientRect(function (data) {
      that.size.height = that.size.height = height - headerHeight - data.height - uni.$u.getPx('32rpx');
    }).exec(function (res) {});
  },
  computed: {},
  methods: {
    endTimeSelect(e){
      this.model.order.end_time = uni.$u.timeFormat(e.value,'yyyy-mm-dd')
    },
    getDetail(id){
        // let house_id = this.model.order.house_id;
        houseOrderDetail({house_order_id : id}).then(res => {
          let data = res.data;
          data.end_time = uni.$u.timeFormat(data.end_time,'yyyy-mm-dd')
          this.model = {order: data};
          this.model.order.house_order_id  = id;
          // this.model.order.month = ''+this.model.order.month;
          // this.model.order.month = parseInt(this.model.order.month);

          this.fileList1 = res.data.payment_voucher;
          this.fileList2 = res.data.lease_agreement;
        })
    },
    submit(){
      let file1 = [];
      this.fileList1.forEach(item => {
        file1.push(item.url)
      });
      this.model.order.payment_voucher = file1;
      let file2 = [];
      this.fileList2.forEach(item => {
        file2.push(item.url)
      });
      this.model.order.lease_agreement = file2;
      console.log(this.model.order)
      let checkedField = [
        'order.name',
        'order.phone',
        'order.id_card',
        'order.month',
        'order.rent',
        'order.lease_agreement',
        'order.end_time',
      ];

      if(this.type === 'apply'){
        checkedField = checkedField.concat([
          'order.payment_voucher',
          'order.bank_name',
          'order.bank_card',
          'order.number'
        ])
      }
      this.$refs.orderForm.validateField(checkedField,(errors) => {
        if(errors.length) {
          uni.$u.toast(errors[0].message)
          return;
        } else {
          if(this.type === 'create'||this.type === 'edit'){
            this.doCreate();
          }else{
            this.doApply();
          }
        }
      })

    },
    doCreate(){
      submitHouseOrder(this.model.order).then(res => {
        if(res.code === 200){
          this.model = {
            order: {
              house_id: '',
              name: '',
              id_card: '',
              phone: '',
              month: '',
              rent: '',
              payment_voucher: '',
              lease_agreement: '',
            }
          };
          this.fileList1 = [];
          this.fileList2 = [];
          this.navTo('/pages/Order/done?type=room');
        }else{
          uni.$u.toast(res.msg)
        }
      })
    },
    doApply(){
      submitApplyHouseOrder(this.model.order).then(res => {
        if(res.code === 200){
          this.model = {
            order: {
              house_id: '',
              name: '',
              id_card: '',
              phone: '',
              month: '',
              rent: '',
              payment_voucher: '',
              lease_agreement: '',
            }
          };
          this.fileList1 = [];
          this.fileList2 = [];
          this.navTo('/pages/Order/done?type=room');
        }else{
          uni.$u.toast(res.msg)
        }
      })
    },
    //上传文件
    async afterFileRead1  (event){
      let lists = [].concat(event.file);

      let fileListLen = this.fileList1.length;
      lists.map((item) => {
        this.fileList1.push({
          ...item,
          status: 'uploading',
          message: '上传中',
        });
      });
      for (let i = 0; i < lists.length; i++) {

        api.uploadOssFile(lists[i].url).then(res => {
          let item = this.fileList1[fileListLen];
          this.fileList1.splice(fileListLen, 1, {
            ...item,
            status: 'success',
            message: '',
            url: res.show_path,
            thumb: res.show_path,
          });
          fileListLen++;
        })
      }
    },
    //上传文件
    async afterFileRead2  (event){
      let lists = [].concat(event.file);

      let fileListLen = this.fileList2.length;
      lists.map((item) => {
        this.fileList2.push({
          ...item,
          status: 'uploading',
          message: '上传中',
        });
      });
      for (let i = 0; i < lists.length; i++) {

        api.uploadOssFile(lists[i].url).then(res => {
          let item = this.fileList2[fileListLen];
          this.fileList2.splice(fileListLen, 1, {
            ...item,
            status: 'success',
            message: '',
            url: res.show_path,
            thumb: res.show_path,
          });
          fileListLen++;
        })
      }
    },
    //删除上传图片
    deleteFile1(event){
      this.fileList1.splice(event.index, 1);
    },
    //删除上传图片
    deleteFile2(event){
      this.fileList2.splice(event.index, 1);
    },
    getUserExtend() {
      userExtends().then((res) => {
            if(res.code === 200) {
              uni.setStorageSync('user', res.data);
              this.$store.commit('userInfo', res.data);
              this.modalShow = !res.data?.phone
                  || !res.data?.name
                  || !res.data?.community
                  || !res.data?.street
                  || !res.data?.company
                  || !res.data?.position
                  || !res.data?.id_card;
              this.model.order.name = res.data.name;
              this.model.order.id_card = res.data.id_card;
              this.model.order.phone = res.data.phone;
            }
      });
    },
    navTo(url) {
      wx.navigateTo({
        url: url
      })
    },
  },
  onPageScroll(res) {

  },
  created() {
    // this.pagePadding = (api.navHeight().navPaddingTop +
    // 	api.navHeight().navHeight + (api.navHeight().headerPadding * 2))
  },
  mounted() {
    let token = uni.getStorageSync('token');
    // this.userInfo = this.$store.userInfo
    if(token && this.type === 'create'){
      this.getUserExtend();
    }
    if(this.type === 'detail' || this.type === 'edit' || this.type === 'apply'){
      this.getDetail(this.model.order.house_order_id );
    }
  }
}
</script>

<style lang="scss">
@import './components/detail.scss';
</style>