<template>
<!--pages/user/editNeeds/index.wxml-->
<view class="edit-needs-box">
  <view class="form-box">
    <form @submit="submit">
    <view class="form-item chose-box acea-row row-between">
      <view class="label">我是供应/需求</view>
      <view> {{form.resourceType == 1 ? '供应' : '需求'}} </view>
    </view>
    <view class="form-item">
      <view class="label">{{form.resourceType == 1 ? '供应' : '需求'}}标题<text class="red">*</text></view>
      <view class="inp-box">
        <input type="text" :placeholder="'我' + (form.resourceType == 1 ? '供应' : '需求') + '...'" :value="form.title" name="title">
      </view>
    </view>
    <view class="form-item">
      <view class="label">{{form.resourceType == 1 ? '供应' : '需求'}}类型<text class="red">*</text></view>
      <!-- <view class="inp-box"><input type="text" placeholder="我供应/需求..." value="{{form.resourceCagetoryId}}" name="resourceCagetoryId" /></view> -->
      <view class="inp-box acea-row-nowrap row-between row-middle">
        <picker class="pick-box" @change="resourcesChange" :value="idx" :range="resourcesList" :range-key="'cagetoryName'" mode="selector">
          <view class="picker">{{resourcesList[resourcesIdx].cagetoryName || '请选择'}}</view>
        </picker>
        <image src="/static/images/home/arrow-r.png" class="arrow-d"></image>
      </view>
    </view>
    <view class="form-item">
      <view class="label acea-row row-between">
       <view>{{form.resourceType == 1 ? '供应' : '需求'}}内容<text class="red">*</text></view> 
       <!-- <view class="colO">看看别人怎么写></view> -->
      </view>
      <view class="area-box">
        <textarea :placeholder="'请详细描述您的' + (form.resourceType == 1 ? '供应' : '需求')" :value="form.detailedDescription" name="detailedDescription"></textarea>
      </view>
    </view>
    <view class="form-item">
      <view class="label">补充内容/添加图片</view>
      <view class="upload-box acea-row">
        <image v-for="(item, index) in form.resourceImgs" :key="index" :src="item" mode="aspectFill"></image>
        <image src="/static/images/upload.png" @tap="upImgs"></image>
      </view>
    </view>
    <view class="form-item">
      <view class="label acea-row row-between">
       <view>{{form.resourceType == 1 ? '供应' : '需求'}}预算<text class="red">*</text></view> 
       <view class="tab-box acea-row ">
        <view :class="'tab-item ' + (active == 1 ? 'tab-a' : '')" data-i="1" @tap="tabClick">明确预算</view>
        <view :class="'tab-item ' + (active == 2 ? 'tab-a' : '')" data-i="2" @tap="tabClick">价格可议</view>
       </view>
      </view>
      <view class="inp-box acea-row-nowrap" v-if="active == 1">
        <input type="text" placeholder="请输入预算" :value="form.capital" @input="capitalChange" name="capital">
        <text>元</text>
      </view>
    </view>
    <view class="form-item">
      <view class="label acea-row row-between">
       <view>展示时间</view> 
      </view>
      <view class="time-box acea-row row-middle">
        <view class="timepick-box">
          <picker @change="startTimeChange" :value="form.resourceStartTime" name="resourceStartTime" mode="date">
            <view class="picker">{{form.resourceStartTime || '请选择'}}</view>
          </picker>
          <image src="/static/images/home/arrow-r.png" class="arrow-d"></image>
        </view>
        <text class="m14">至</text>
        <view class="timepick-box">
          <picker @change="endTimeChange" :value="form.resourceEndTime" name="resourceEndTime" mode="date">
            <view class="picker">{{form.resourceEndTime || '请选择'}}</view>
          </picker>
          <image src="/static/images/home/arrow-r.png" class="arrow-d"></image>
        </view>
      </view>
    </view>
		<view class="btn-box acea-row row-center">
			<button class="submit-btn default-btn" form-type="submit" data-type="0">保存到草稿箱</button>
			<button class="submit-btn" form-type="submit" data-type="1">保存并提交</button>
		</view>
  </form>
  </view>
  
</view>
</template>

<script>
// pages/user/editNeeds/index.js
const util = require("../../../utils/util.js");
const app = getApp();
import WxValidate from '../../../utils/WxValidate.js';

export default {
  data() {
    return {
      form: {
        resourceType: 0,
        title: '',
        detailedDescription: '',
        resourceImgs: [],
        capital: '',
        resourceStartTime: '',
        resourceEndTime: ''
      },
      id: '',
      active: 1,
      resourcesList: [],
      resourcesIdx: null
    };
  },
  components: {},
  props: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.id) {
      this.setData({
        id: options.id
      });
      this.getDetail(options.id);
    }
    if (options.type) {
      this.setData({//['form.resourceType']: Number(options.type)
      });
      //try fix
      this.form.resourceType = Number(options.type);
    }
    this.initValidate(); //验证规则函数

    this.getResourcesCagetory();
  },
  methods: {
    tabClick(e) {
      let i = e.currentTarget.dataset.i;

      if (i == 2) {
        this.setData({//['form.capital']: '价格可议'
        });
        //try fix
        this.form.capital = '价格可议';
      }

      this.setData({
        active: e.currentTarget.dataset.i
      });
    },

    capitalChange(e) {
      this.setData({//['form.capital']: e.detail.value
      });
      //try fix
      this.form.capital = e.detail.value;
    },

    startTimeChange(e) {
      console.log(e.detail.value);
      let timeArr = e.detail.value.split('-');
      let year = Number(timeArr[0]) + 1;
      this.setData({//['form.resourceStartTime']: e.detail.value
        //['form.resourceEndTime']: year + '-' + timeArr[1] + '-' + timeArr[2]
      });
      //try fix
      this.form.resourceEndTime = year + '-' + timeArr[1] + '-' + timeArr[2];
      //try fix
      this.form.resourceStartTime = e.detail.value;
    },

    endTimeChange(e) {
      this.setData({//['form.resourceEndTime']: e.detail.value
      });
      //try fix
      this.form.resourceEndTime = e.detail.value;
    },

    bindPickerChange(e) {
      this.setData({//['form.resourceType']: this.data.typeArr[e.detail.value]
      });
      //try fix
      this.form.resourceType = this.typeArr[e.detail.value];
    },

    //获取供应、需求类型
    getResourcesCagetory() {
      app.http('GET', 'ResourcesCagetory/listResourcesCagetory').then(res => {
        // console.log(res)
        if (res.data.success) {
          this.setData({
            resourcesList: res.data.data
          });
        }
      });
    },

    resourcesChange(e) {
      // console.log(e)
      let idx = Number(e.detail.value);
      // this.setData({//['form.resourceCagetoryId']: this.data.resourcesList[idx].id
      //   resourcesIdx: idx,
      // });
			this.resourcesIdx = idx;
      //try fix
      this.form.resourceCagetoryId = this.resourcesList[idx].id;
    },

    // 重新发布，获取提交数据
    getDetail(id) {
      app.http('GET', 'Resources/resourceInfo', {
        id: id
      }).then(res => {
        if (res.data.success) {
          let data = res.data.data;
          this.setData({//['form.resourceType']: data.resourceType
            //['form.title']: data.title
            //['form.detailedDescription']: data.detailedDescription
            //['form.resourceImgs']: data.resourceImgs
            //['form.capital']: data.capital
            //['form.resourceStartTime']: data.resourceStartTime
            //['form.resourceEndTime']: data.resourceEndTime
          });
          //try fix
          this.form.resourceEndTime = data.resourceEndTime;
          //try fix
          this.form.resourceStartTime = data.resourceStartTime;
          //try fix
          this.form.capital = data.capital;
          //try fix
          this.form.resourceImgs = data.resourceImgs;
          //try fix
          this.form.detailedDescription = data.detailedDescription;
          //try fix
          this.form.title = data.title;
          //try fix
          this.form.resourceType = data.resourceType;

          if (isNaN(Number(data.capital))) {
            this.setData({
              active: 2
            });
          }
        }
      });
    },

    initValidate() {
      const rules = {
        title: {
          required: true
        },
        resourceCagetoryId: {
          required: true
        },
        detailedDescription: {
          required: true
        },
        resourceStartTime: {
          required: true
        },
        resourceEndTime: {
          required: true
        }
      };
      const messages = {
        title: {
          required: '请填写标题'
        },
        resourceCagetoryId: {
          required: '请选择需求类型'
        },
        detailedDescription: {
          required: '请填写内容'
        },
        resourceEndTime: {
          required: '请设置展示开始时间'
        },
        resourceEndTime: {
          required: '请设置展示结束时间'
        }
      };
      this.WxValidate = new WxValidate(rules, messages);
    },

    upImgs() {
      util.chooseImages2(img => {
        let imgs = this.form.resourceImgs;
        imgs.push(img);
        this.setData({//['form.resourceImgs']: imgs
        });
        //try fix
        this.form.resourceImgs = imgs;
      });
    },

    submit(e) {
      let that = this;
      let type = e.detail.target.dataset.type;
      let params = e.detail.value;
      if (this.id != '') {
        params.id = this.id;
      }
      params.resourceType = that.form.resourceType;
      params.resourceCagetoryId = that.form.resourceCagetoryId;
      params.resourceImgs = that.form.resourceImgs;
      params.capital = that.form.capital;

      if (type == 0) {
        params.isDraft = true;
        uni.showModal({
          title: '提示！',
          content: '是否保存到草稿箱？',

          success(res) {
            if (res.confirm) {
              if (!that.WxValidate.checkForm(params)) {
                const error = that.WxValidate.errorList[0];
                that.showModal(error);
                return false;
              }

              that.submitHttp(params);
            } else {
              console.log('已取消');
            }
          }

        });
      } else {
        uni.showModal({
          title: '提示！',
          content: '是否确认提交？',

          success(res) {
            if (res.confirm) {
              params.isDraft = false;

              if (!that.WxValidate.checkForm(params)) {
                const error = that.WxValidate.errorList[0];
                that.showModal(error);
                return false;
              }

              that.submitHttp(params);
            } else {
              console.log('已取消');
            }
          }

        });
      }
    },

    submitHttp(params) {
      app.http('post', 'Resources/create', params).then(res => {
        if (res.data.success) {
          uni.showToast({
            title: '提交成功',
            duration: 2000
          });
          setTimeout(() => {
            uni.navigateBack({
              delta: 1
            });
          }, 2000);
        } else {
          uni.showToast({
            title: '请求失败',
            duration: 2000,
            icon: 'none'
          });
        }
      });
    },

    showModal(error) {
      uni.showModal({
        content: error.msg,
        showCancel: false
      });
    }

  }
};
</script>
<style>
/* pages/user/editNeeds/index.wxss */
.form-box{
  width: 100%;
  padding: 32rpx 38rpx;
  font-size: 28rpx;
  color:#666666;
}
.form-item{
  margin-bottom: 20rpx;
}

.red{
  color: #FF0000;
}
.colO{
  color: #FF6D31;
  font-size: 24rpx;
}
.inp-box{
  width: 100%;
  padding: 10rpx 22rpx;
  background: #eee;
  color: #666;
  margin-top: 26rpx;
}
.pick-box{
  width: 92%;
  background: #eee;
  box-sizing: border-box;
  /* padding: 10rpx 22rpx; */
}
.pick-box .picker{
  width: 100%;
  color: #666666;
}
.inp-box input{
  width: 90%;
  height: 100%;
}
.area-box{
  width: 100%;
  height: 290rpx;
  padding: 24rpx 22rpx;
  background: #eee;
  color: #666;
  margin-top: 36rpx;
}
.area-box textarea{
  width: 100%;
  height: 100%;
}
.upload-box{
  width: 100%;
  height: 140rpx;
  margin-top: 26rpx;
}
.upload-box image{
  width: 140rpx;
  height: 140rpx;
  margin-right: 12rpx;
}

.tab-item{
  width: 122rpx;
  height: 40rpx;
  text-align: center;
  line-height: 40rpx;
  border: 1px solid #707070;
  border-radius: 8rpx;
  color: #666;
  font-size: 22rpx;
  margin-left: 20rpx;
}
.tab-a{
   background: linear-gradient(341deg, #FF5100 0%, #FFA782 100%);
   color: #fff;
   border: none;
}
.time-box{
  margin-top: 24rpx;
}
.timepick-box{
  width: 308rpx;
  height: 60rpx;
  background: #eee;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20rpx;
}
.timepick-box picker{
  width: 100%;
}
.arrow-d{
  width: 14rpx;
  height: 24rpx;
  transform: rotate(90deg);
}
.m14{
  margin: 0 14rpx;
}
.submit-btn{
  width: 240rpx !important;
  height: 76rpx !important;
  background: linear-gradient(144deg, #FFA782 0%, #FF5100 100%);
  border-radius: 38rpx;
  color: #fff;
  font-size: 28rpx !important;
  line-height: 76rpx !important;
  text-align: center;
  margin:40rpx auto 20rpx !important;
  padding: 0 !important;
}
.default-btn{
	background: #BFBFBF;
}
</style>