import { post,api_url } from "../../../../utils/http";

// pages/recordSheet/components/inspect/inspect.js
Component({
  /**
   * 组件的属性列表
   */
  options: {
    addGlobalClass: true
  },
  properties: {
    preCheck: {
      type: Object,
      value: null,
      observer(newVal,oldVal) {
        if(newVal) {
          console.log(newVal)
          console.log(newVal.option_list)
          newVal.option_list.forEach((item,index)=> {
            item.children.forEach((newItem) => {
              console.log(newItem)
              newItem.status = true
            })
          })
          this.setData({
            check: newVal
          })
          console.log(this.data.check)
        }
        console.log(newVal,oldVal)
        // this.setData({
        //   check
        // })
      }
    },
    check_id: {
      type: String,
      value: null,
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    is_list: true,
    list: ['','','',''],
    more: true,
    maxlength: 500,
    number: 0,
    value: "",
    imgs: [],
    check: {}
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onOpenList() {
      this.setData({
        more: false
      })
    },

    /**
     * 切换结果
    */
    onChangeStatus(e) {
      let { idx,index,status } = e.currentTarget.dataset;
      this.setData({
        ['check.option_list[' + idx + '].children['+index+'].status']: status == 'true' ? true : false
      })
    },

    /** 监听文本域 */
    bindTextAreaInput(e) {
      this.setData({
        number: e.detail.cursor,
        value: e.detail.value
      })
    },

    /** 选择图片 */
    chooseImage() {
      let that = this;
      let imgs = this.data.imgs;
      let count = 9 - this.data.imgs.length
      wx.chooseImage({
        count,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success (res) {
          wx.showLoading({
            title: '正在上传图片',
            mask: true
          });
          const tempFiles = res.tempFiles
          tempFiles.forEach((item) => {
            that.upload(item.path).then((data) => {
              imgs.push({
                type: 'image',
                url: data.data.url,
              })
              that.setData({ imgs })
              wx.hideLoading()
            });
          })
          
        }
      })
    },

    /** 选择视频 */
    chooseVideo(){
      let that = this;
      let imgs = this.data.imgs;
      wx.chooseMedia({
        count: 1,
        mediaType: ['video'],
        sourceType: ['album', 'camera'],
        maxDuration: 30,
        camera: 'back',
        success(res) {
          wx.showLoading({
            title: '正在上传视频',
            mask: true
          });
          const tempFiles = res.tempFiles
          that.upload(tempFiles[0].thumbTempFilePath).then((data) => {
            if(imgs.length > 0 && imgs[0].type == 'video') {
              that.setData({
                ['imgs[' + 0 + '].thumb']: data.data.url
              })
            } else {
              imgs.unshift({
                type: 'video',
                thumb: data.data.url,
                url: ''
              })
              that.setData({ imgs })
            }
            // that.setData({ imgs })
            wx.hideLoading()
          });
          that.upload(tempFiles[0].tempFilePath).then((data) => {
            if(imgs.length > 0 && imgs[0].type == 'video') {
              that.setData({
                ['imgs[' + 0 + '].url']: data.data.url
              })
            } else {
              imgs.unshift({
                type: 'video',
                thumb: '',
                url: data.data.url
              })
              that.setData({ imgs })
            }
            // imgs.unshift({
            //   type: 'video',
            //   thumb: tempFiles[0].thumbTempFilePath,
            //   url: data.data.url
            // })
            // that.setData({ imgs })
            wx.hideLoading()
          });
        }
      })
    },

    /** 上传视频/图片 */
    upload(filePath) {
      let that = this;
      // 上传类型/业务类型:avatar头像,order订单反馈,check检查表反馈
      return new Promise((resolve,reject) => {
        let { imgs } = this.data;
        wx.uploadFile({
          url: `${api_url}api/upload`,
          // url: 'https://store.test-api.ijolijoli.com/api/upload',
          header: {
            token: wx.getStorageSync('token') || '',
          },
          filePath,
          name: 'file',
          formData: {
            'type': 'check'
          },
          success(res) {
            console.log(res)
            if(res.statusCode == 200 && res.data) {
              let data = JSON.parse(res.data);
              if(data.code == 200 && data.data) {
                resolve(data)
              } else {
                wx.showToast({
                  title: '上传失败',
                  icon: 'none'
                })
              }
            } else {
              wx.showToast({
                title: '上传失败',
                icon: 'none'
              })
            }
          },
          fail(err) {
            wx.showToast({
              title: '上传失败',
              icon: 'none'
            })
          }
        })
      })
    },

    /**
     * 删除列表项
    */
    onDeleteItem(e) {
      let imgs = this.data.imgs;
      if(this.data.is_list) {
        imgs = this.data.check.feedback.media_list
      }
      imgs.splice(e.currentTarget.dataset.index, 1);
      this.setData({ imgs })
      console.log(imgs)
    },

    /**
     * /api/check/update
     * 添加/修改检查信息
    */
    onCheckUpdate() {
      let { orderId,value,imgs,check,check_id } = this.data;
      let option_ids = [], option_values= [];
      check.option_list.forEach((item,index) => {
        item.children.forEach((newItem,index) => {
          option_ids.push(newItem.id)
          if(newItem.status) {
            option_values.push(1)
          } else {
            option_values.push(2)
          }
        })
      })
      post('api/check/update',{
        check_id,
        type: check.type,
        option_ids: option_ids.toString(),
        option_values: option_values.toString(),
        content: value,
        media_list: JSON.stringify(imgs)
      },(res) => {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
        setTimeout(() => {
          let pages=getCurrentPages()
          let prePage = pages[pages.length-1]
          prePage.onShow()
          this.setData({
            is_list: true
          })
        }, 1500);
        console.log(res)
      })
    },

    /** 预览图片和视频 */
    previewMedia(e) {
      let arr = this.data.imgs
      if(this.data.is_list) {
        arr = this.data.check.feedback.media_list
      }
      let current = e.currentTarget.dataset.index
      wx.previewMedia({
        sources: arr,
        current
      })
    },

    /** 切换编辑 */
    onChangeEdit() {
      this.setData({
        is_list: false
      })
    }

  }
})