<template>
  <view>
    <cpn-navbar title="长护险回访" :is-back="true"></cpn-navbar>

    <view class="container">
      <u-form :model="form" ref="uForm" :label-width="200" :error-type="['message', 'border-bottom']">
        <u-form-item label="服务满意度" prop="satisfy">
          <u-radio-group v-model="form.satisfy">
            <u-radio v-for="(item, index) in satisfies" :key="item.value" :name="item.value">
              {{ item.label }}
            </u-radio>
          </u-radio-group>
        </u-form-item>
        <u-form-item label="护理员护理情况调查" prop="nurse_investigate">
          <u-radio-group v-model="form.nurse_investigate">
            <u-radio v-for="(item, index) in nurseInvestigates" :key="item.value" :name="item.value">
              {{ item.label }}
            </u-radio>
          </u-radio-group>
        </u-form-item>
        <u-form-item label="是否在岗" prop="is_work">
          <u-switch v-model="form.is_work" :active-value="1" :inactive-value="0"></u-switch>
        </u-form-item>
        <u-form-item label="按照排班时间上门服务" prop="is_on_time">
          <u-switch v-model="form.is_on_time" :active-value="1" :inactive-value="0"></u-switch>
        </u-form-item>
        <u-form-item label="护理工具携带" prop="tools">
          <u-checkbox-group ref="tools" @change="e => checkboxChange(e,'tools')">
            <u-checkbox v-for="(item, index) in tools" :key="index" :name="item.name" v-model="item.checked">
              {{ item.name }}
            </u-checkbox>
            <u-checkbox :name="otherTool.name" v-model="otherTool.checked">
              <view style="display: flex;align-items: center;">
                <text style="word-break: keep-all;">其他</text>
                <u-input style="margin-left: 10rpx;" v-model="otherTool.name" @input="inputRefreshCheckbox('tools')"></u-input>
              </view>
            </u-checkbox>
          </u-checkbox-group>
        </u-form-item>
        <u-form-item label="是否有工作服">
          <u-switch v-model="temp1" @change="clothesChange"></u-switch>
        </u-form-item>
        <u-form-item label="是否有工作证">
          <u-switch v-model="temp2" @change="cardChange"></u-switch>
        </u-form-item>
        <u-form-item label="服务内容" prop="serve">
          <u-checkbox-group ref="serve" @change="e => checkboxChange(e,'serve')">
            <u-checkbox v-for="(item, index) in serves" :key="index" :name="item.name" v-model="item.checked">
              {{ item.name }}
            </u-checkbox>
            <u-checkbox :name="otherServe.name" v-model="otherServe.checked">
              <view style="display: flex;align-items: center;">
                <text style="word-break: keep-all;">其他</text>
                <u-input style="margin-left: 10rpx;" v-model="otherServe.name" @input="inputRefreshCheckbox('serve')"></u-input>
              </view>
            </u-checkbox>
          </u-checkbox-group>
        </u-form-item>
        <u-form-item label="其他需求" prop="other">
          <u-checkbox-group ref="other" @change="e => checkboxChange(e,'other')">
            <u-checkbox v-for="(item, index) in others" :key="index" :name="item.name" v-model="item.checked">
              {{ item.name }}
            </u-checkbox>
            <u-checkbox :name="otherOther.name" v-model="otherOther.checked">
              <view style="display: flex;align-items: center;">
                <text style="word-break: keep-all;">其他</text>
                <u-input style="margin-left: 10rpx;" v-model="otherOther.name" @input="inputRefreshCheckbox('other')"></u-input>
              </view>
            </u-checkbox>
          </u-checkbox-group>
        </u-form-item>
        <u-form-item label="建议" prop="tip">
          <u-input v-model="form.tip" type="textarea"></u-input>
        </u-form-item>
        <u-form-item label="回访图片">
          <u-upload ref="uUpload" :custom-btn="true" :action="action" :file-list="fileList"
                    :source-type="['camera']">
            <view slot="addBtn" class="slot-btn" hover-class="slot-btn__hover" hover-stay-time="150">
              <u-icon name="camera" size="60" color="#c0c4cc" label="点击拍摄" label-pos="bottom"></u-icon>
            </view>
          </u-upload>
        </u-form-item>
        <u-form-item label="服务对象/家属签名" required prop="sign_image_id">
          <view>
            <u-button type="primary" size="mini" :throttle-time="3000" @click="pageTo('/pages/sign/sign?key=vuex_sign_image')">点击签名</u-button>
            <image v-if="vuex_sign_image || (detail.sign_image && detail.sign_image.url)"
                   :src="vuex_sign_image || (detail.sign_image && detail.sign_image.url)"
                   style="width: 260rpx;object-fit: cover;transform: rotate(270deg);"
                   @click="showimg(vuex_sign_image || (detail.sign_image && detail.sign_image.url))"></image>
          </view>
        </u-form-item>
        <u-form-item label="调查人员签名" required prop="admin_sign_image_id">
          <view>
            <u-button type="primary" size="mini" :throttle-time="3000" @click="pageTo('/pages/sign/sign?key=vuex_admin_sign_image')">点击签名</u-button>
            <image v-if="vuex_admin_sign_image || (detail.admin_sign_image && detail.admin_sign_image.url)"
                   :src="vuex_admin_sign_image || (detail.admin_sign_image && detail.admin_sign_image.url)"
                   style="width: 260rpx;object-fit: cover;transform: rotate(270deg);"
                   @click="showimg(vuex_admin_sign_image || (detail.admin_sign_image && detail.admin_sign_image.url))"></image>
          </view>
        </u-form-item>
        <u-form-item label="所在位置">
          <view>
            <u-button type="primary" size="mini" :throttle-time="3000" @click="getLoaction">获取位置</u-button>
            <view style="word-break: break-all;">
              {{ `${(form.lng || form.lat) ? ('(' + form.lng + ',' + form.lat + ')') : ''}${form.address}` }}
            </view>
          </view>
        </u-form-item>
      </u-form>
      <u-button type="primary" @click="submit">提交</u-button>
    </view>
  </view>
</template>

<script>
import QQMapWX from '@/libs/qqmap-wx-jssdk.js'
import { ROOTPATH } from "@/common/config"
export default {
  data() {
    return {
      temp1: false,
      temp2: false,
      action: `${ROOTPATH}/api/admin/upload-file`,
      fileList: [],
      id: "",
      type: "add",
      detail: {},
      form: {
        customer_id: "",
        satisfy: 1,
        nurse_investigate: 1,
        is_work: 1,
        is_on_time: 1,
        tools: [],
        accessory: "",
        serve: "",
        other: "",
        tip: "",
        sign_image_id: "",
        admin_sign_image_id: "",
        remark: "",
        file_ids: [],
        lat: "",
        lng: "",
        address: ""
      },
      rules: {
        sign_image_id: [
          {
            validator: (rule, value, callback) => {
              if (this.vuex_sign_image || value) {
                callback()
              } else {
                callback(new Error('请签名'))
              }
            }
          }
        ],
        admin_sign_image_id: [
          {
            validator: (rule, value, callback) => {
              if (this.vuex_admin_sign_image || value) {
                callback()
              } else {
                callback(new Error('请签名'))
              }
            }
          }
        ]
      },
      satisfies: [
        {
          label: "90分以上",
          value: 1
        },
        {
          label: "80-90分",
          value: 2
        },
        {
          label: "80分以下",
          value: 3
        },
      ],
      nurseInvestigates: [
        {
          label: "护理中回访",
          value: 1
        },
        {
          label: "日常回访",
          value: 2
        },
      ],
      tools: [
          {
            name: '护理包',
            checked: false
          },
          {
            name: '服务计划表',
            checked: false
          },
          {
            name: '血压器',
            checked: false
          },
          {
            name: '理发器',
            checked: false
          }
      ],
      otherTool: {
        name: undefined,
        checked: false
      },
      serves: [
        {
          name: '理发',
          checked: false
        },
        {
          name: '整理',
          checked: false
        },
        {
          name: '康复训练',
          checked: false
        },
        {
          name: '洗澡',
          checked: false
        },
        {
          name: '按摩',
          checked: false
        },
        {
          name: '个人卫生清洁',
          checked: false
        },
        {
          name: '协助指导',
          checked: false
        },
        {
          name: '生活照料',
          checked: false
        }
      ],
      otherServe: {
        name: undefined,
        checked: false
      },
      others: [
        {
          name: '陪诊',
          checked: false
        },
        {
          name: '康养',
          checked: false
        },
        {
          name: '陪护',
          checked: false
        }
      ],
      otherOther: {
        name: undefined,
        checked: false
      }
    };
  },
  methods: {
    showimg(url) {
      if (url)
        this.$showimg({
          imgs: [url],
          current: 0
        })
    },
    pageTo (url) {
      uni.navigateTo({
        url
      })
    },
    clothesChange (e) {
      let arr = this.form.accessory.split('|').filter(i => i?.trim());
      if (e) {
        if (!arr.includes('工作服')) {
          arr.push('工作服');
        }
      } else {
        arr = arr.filter(i => i !== '工作服');
      }
      this.form.accessory = arr.reduce((pre, cur, index) => (pre + (index === 0 ? cur : `|${cur}`)),'')
    },
    cardChange (e) {
      let arr = this.form.accessory.split('|').filter(i => i?.trim());
      if (e) {
        if (!arr.includes('工作证')) {
          arr.push('工作证');
        }
      } else {
        arr = arr.filter(i => i !== '工作证');
      }
      this.form.accessory = arr.reduce((pre, cur, index) => (pre + (index === 0 ? cur : `|${cur}`)),'')
    },
    checkboxChange (e,key) {
      let arr = e.filter(i => i?.trim())
      this.form[key] = arr.reduce((pre, cur, index) => (pre + (index === 0 ? cur : `|${cur}`)),'')
    },
    inputRefreshCheckbox (refName) {
      this.$refs[refName].emitEvent()
    },
    load() {
      this.qqmapsdk = new QQMapWX({
        key: 'D5EBZ-C3BWP-HZIDG-VO6BE-P2MN5-ESFZO'
      });
    },
    getLoaction() {
      return new Promise((resolve, reject) => {
        uni.getLocation({
          type: 'gcj02',
          isHighAccuracy: true
        }).then(res => {
          if (res[1]) {
            this.form.lat = res[1]?.latitude
            this.form.lng = res[1]?.longitude

            this.qqmapsdk.reverseGeocoder({
              location: {
                latitude: this.form.lat,
                longitude: this.form.lng
              },
              success: (res) => {
                this.form.address = res.result.address + res.result.formatted_addresses.recommend
                console.log(this.form)
                resolve(res)
              },
              fail: (err) => {
                reject(err)
              }
            })
          } else {
            uni.showToast({
              icon: 'none',
              title: '操作频繁,请稍后再试'
            })
            reject(res)
            console.log(res);
          }
        })
      })
    },

    submit () {
      const uploadSignImage = () => {
        return new Promise((resolve, reject) => {
          if (this.vuex_sign_image) {
            uni.uploadFile({
              url: `${ROOTPATH}/api/admin/upload-file`,
              header: {
                Authorization: `Bearer ${this.vuex_token}`
              },
              filePath: this.vuex_sign_image,
              name: 'file',
              success: (res) => {
                if (res.statusCode === 200) {
                  const response = JSON.parse(res.data)
                  resolve(response)
                } else {
                  reject(res.data)
                }
              },
              fail: (err) => {
                reject(err)
              }
            })
          } else {
            resolve()
          }
        })
      }
      const uploadAdminSignImage = () => {
        return new Promise((resolve, reject) => {
          if (this.vuex_admin_sign_image) {
            uni.uploadFile({
              url: `${ROOTPATH}/api/admin/upload-file`,
              header: {
                Authorization: `Bearer ${this.vuex_token}`
              },
              filePath: this.vuex_admin_sign_image,
              name: 'file',
              success: (res) => {
                if (res.statusCode === 200) {
                  const response = JSON.parse(res.data)
                  resolve(response)
                } else {
                  reject(res.data)
                }
              },
              fail: (err) => {
                reject(err)
              }
            })
          } else {
            resolve()
          }
        })
      }
      this.$refs.uForm.validate(valid => {
        if (valid) {
          Promise.all([uploadSignImage(),uploadAdminSignImage()]).then(res => {
            console.log(res)
            if (res[0]?.id) {
              this.form.sign_image_id = res[0].id
            }
            if (res[1]?.id) {
              this.form.admin_sign_image_id = res[1].id
            }
            this.form.file_ids = this.$refs.uUpload.lists.filter(i => i.progress === 100).map(i => i.response?.id)
            if (this.type === 'add') {
              delete this.form.id
            } else {
              this.form.id = this.id
            }
            this.$u.api.adminSaveLongInsurance(this.form).then(res => {
              uni.showToast({
                icon: 'success',
                title: '保存成功',
              })
              setTimeout(() => {
                uni.navigateBack()
              },1500)
            })
          }).catch(err => {
            console.error(err)
            uni.showToast({
              title: "签名保存失败",
              icon: "none"
            })
          })
        }
      })
    },

    async getDetail () {
      const res = await this.$u.api.adminLongInsuranceDetail(this.id)
      this.detail = res;
      for (let key in this.form) {
        this.form[key] = res[key]
      }
      console.log(this.form)
      this.fileList = res.files.map(i => ({
        url: i.url,
        response: i
      }))
      this.temp1 = /工作服/g.test(res.accessory)
      this.temp2 = /工作证/g.test(res.accessory)
      let resTools = res.tools?.split('|')?.filter(i => i.trim())
      this.tools.forEach(item => {
        item.checked = res.tools?.indexOf(item.name) !== -1
      })
      this.otherTool.name = resTools?.find(i => !this.tools.find(j => j.name === i))
      this.otherTool.checked = !!this.otherTool.name
      //serve
      let resServes = res.serve?.split('|')?.filter(i => i.trim())
      this.serves.forEach(item => {
        item.checked = res.serve?.indexOf(item.name) !== -1
      })
      this.otherServe.name = resServes?.find(i => !this.serves.find(j => j.name === i))
      this.otherServe.checked = !!this.otherServe.name
      //other
      let resOthers = res.other?.split('|')?.filter(i => i.trim())
      this.others.forEach(item => {
        item.checked = res.other?.indexOf(item.name) !== -1
      })
      this.otherOther.name = resOthers?.find(i => !this.others.find(j => j.name === i))
      this.otherOther.checked = !!this.otherOther.name
    }
  },
  onLoad(option) {
    this.form.customer_id = option.customer_id;
    this.id = option.id;
    this.type = option.id ? 'edit' : 'add';
    if (this.type === 'edit') {
      this.getDetail()
    }
  },
  onReady() {
    this.load();
    this.$refs.uForm.setRules(this.rules);
  },
}
</script>

<style lang="scss">
.container {
  border-radius: 10rpx;
  background: #FFFFFF;
  box-shadow: 0rpx 4rpx 10rpx 0rpx rgba(219, 218, 218, 0.5);
  margin: 20rpx;
  padding: 20rpx;
}

.slot-btn {
  width: 200rpx;
  height: 200rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgb(244, 245, 246);
  border: 2rpx #108cff solid;
  border-radius: 10rpx;
  box-sizing: content-box;
  filter: drop-shadow(0 0 4rpx #0fc7ff) drop-shadow(0 0 6rpx #00eaff);
}
.slot-btn__hover {
  background-color: rgb(235, 236, 238);
}

</style>
