<template>
  <div class="mcSubmit">
    <van-form @submit="onSubmit" ref="submits" style="background: #fff">
      <van-cell-group style="margin: none" inset>
        <div class="myTitle required"><span class="number">01</span>{{ t('feedback.title1') }}</div>
        <van-field
          class="zdycell"
          v-model="formData.problemDesc"
          label-align="top"
          name="故障描述"
          label=""
          rows="2"
          autoSize
          :max-count="5"
          type="textarea"
          maxlength="500"
          show-word-limit
          :rules="[
            { name: 'problemDesc', validator: validator, trigger: 'onChange', message: t('feedback.settext') + t('feedback.title1') },
          ]"
          :placeholder="t('feedback.settext')"
        />
        <van-field class="uploadercell" name="uploader" label-align="top">
          <template #input>
            <div>
              <div>
                <van-uploader
                  upload-icon="plus"
                  :before-read="beforeRead"
                  :after-read="clzpAfterRead"
                  accept=".jpg,.png,.mp4"
                  :max-count="6"
                  v-model="formData.problemDescImgs"
                />
              </div>
              <div class="tips" v-html="t('feedback.fileTipsPc')"></div>
            </div>
          </template>
        </van-field>
        <div class="myTitle required"><span class="number">02</span>{{ t('feedback.title2') }}</div>
        <van-field
          v-model="formData.solution"
          label-align="top"
          class="zdycell"
          name="故障描述"
          label=""
          rows="2"
          autoSize
          type="textarea"
          maxlength="500"
          show-word-limit
          :rules="[{ name: 'solution', validator: validator, trigger: 'onChange', message: t('feedback.settext') + t('feedback.title2') }]"
          :placeholder="t('feedback.settext')"
        />
        <van-field class="uploadercell" name="uploader" label-align="top">
          <template #input>
            <div>
              <div>
                <van-uploader
                  upload-icon="plus"
                  class="uploadercell"
                  :before-read="beforeRead"
                  :after-read="clzpAfterRead"
                  :max-count="6"
                  v-model="formData.solutionImgs"
                />
              </div>
              <div class="tips" v-html="t('feedback.fileTipsPc')"></div>
            </div>
          </template>
        </van-field>
        <div class="myTitle required"><span class="number">03</span>{{ t('feedback.title3') }}</div>
        <van-field
          v-model="setObjId.industryOptionId"
          class="zdycell"
          is-link
          readonly
          name="picker"
          label=""
          :placeholder="t('feedback.setselcet')"
          :rules="[{ required: true, message: t('feedback.setselcet') + t('feedback.title3') }]"
          @click="showPicker.industryOptionId = true"
        />
        <van-popup v-model:show="showPicker.industryOptionId" position="bottom">
          <van-picker
            :columns="propsOptions.industryOptionId"
            @confirm="(val) => onConfirm(val, 'industryOptionId')"
            @cancel="showPicker.industryOptionId = false"
          />
        </van-popup>
        <div class="myTitle required"><span class="number">04</span>{{ t('feedback.title4') }}</div>
        <van-field
          class="zdycell"
          v-model="setObjId.hardwareOptionId"
          is-link
          readonly
          name="picker"
          label=""
          :placeholder="t('feedback.setselcet')"
          :rules="[{ required: true, message: t('feedback.setselcet') + t('feedback.title4') }]"
          @click="showPicker.hardwareOptionId = true"
        />
        <van-popup v-model:show="showPicker.hardwareOptionId" position="bottom">
          <van-picker
            :columns="propsOptions.hardwareOptionId"
            @confirm="(val) => onConfirm(val, 'hardwareOptionId')"
            @cancel="showPicker.hardwareOptionId = false"
          />
        </van-popup>
        <div class="myTitle required"><span class="number">05</span>{{ t('feedback.title5') }}</div>
        <van-field
          class="zdycell"
          v-model="setObjId.softwareOptionId"
          is-link
          readonly
          name="picker"
          label=""
          maxlength="30"
          :placeholder="t('feedback.setselcet')"
          :rules="[{ required: true, message: t('feedback.setselcet') + t('feedback.title5') }]"
          @click="showPicker.softwareOptionId = true"
        />
        <van-popup v-model:show="showPicker.softwareOptionId" position="bottom">
          <van-picker
            :columns="propsOptions.softwareOptionId"
            @confirm="(val) => onConfirm(val, 'softwareOptionId')"
            @cancel="showPicker.softwareOptionId = false"
          />
        </van-popup>
        <div class="myTitle"><span class="number">06</span>{{ t('feedback.title6') }}</div>
        <van-field
          class="zdycell"
          v-model="formData.nickName"
          label-align="top"
          name="联系电话"
          maxlength="15"
          label=""
          :placeholder="t('feedback.settext')"
        />
        <div class="myTitle"><span class="number">07</span>{{ t('feedback.title61') }}</div>
        <van-field
          class="zdycell"
          v-model="formData.phone"
          label-align="top"
          name="联系电话"
          maxlength="11"
          label=""
          :placeholder="t('feedback.settext')"
        />
        <div class="myTitle"><span class="number">08</span>{{ t('feedback.title7') }}</div>
        <van-field
          v-model="formData.country"
          is-link
          class="zdycell"
          readonly
          name="picker"
          label=""
          :placeholder="t('feedback.setselcet')"
          @click="showPicker.country = true"
        />
        <van-popup v-model:show="showPicker.country" position="bottom">
          <van-picker :columns="columnsCountry" @confirm="(val) => onConfirm(val, 'country')" @cancel="showPicker.country = false" />
        </van-popup>
        <div class="myTitle" v-if="formData.country == '中国' || formData.country == 'China'"
          ><span class="number">{{ formData.country == '中国' || formData.country == 'China' ? '09' : '08' }}</span
          >{{ t('feedback.title71') }}</div
        >
        <van-field
          v-if="formData.country == '中国' || formData.country == 'China'"
          v-model="formData.city"
          class="zdycell"
          is-link
          readonly
          name="area"
          label=""
          :placeholder="t('feedback.setselcet')"
          @click="showPicker.city = true"
        />
        <van-popup v-model:show="showPicker.city" position="bottom">
          <van-cascader
            v-model="cascaderValue"
            title="请选择所在地区"
            :options="columnsCity"
            @close="showPicker.city = false"
            @finish="onFinish"
          />
        </van-popup>
        <div class="myTitle"
          ><span class="number">{{ formData.country == '中国' || formData.country == 'China' ? '10' : '09' }}</span
          >{{ t('feedback.title8') }}</div
        >
        <van-field class="ratecell" name="rate" label="">
          <template #input>
            <van-rate size="30" color="#FADB14" void-color="#D9D9D9" :allow-half="true" v-model="formData.score" />
          </template>
        </van-field>
        <div class="myTitle"
          ><span class="number">{{ formData.country == '中国' || formData.country == 'China' ? '11' : '10' }}</span
          >{{ t('feedback.title9') }}</div
        >
        <van-field
          v-model="formData.scoreReason"
          class="zdycell"
          label-align="top"
          name="联系电话"
          maxlength="100"
          label=""
          :placeholder="t('feedback.settext')"
        />
        <div style="margin: 54px 0 24px 0; background-color: #f5f5f5">
          <van-button style="height: 44px" block color="#00B3EC" type="primary" native-type="submit"> 提交 </van-button>
        </div>
      </van-cell-group>
    </van-form>
  </div>
</template>

<script setup>
  import { ref, watch } from 'vue';
  import cityList from './area.json';
  import countryList from './country.json';
  import axios from 'axios';
  const areaList = ref({});
  const props = defineProps(['columns', 'addres']);
  const emit = defineEmits(['submit']);
  import { showToast } from 'vant';
  const propsOptions = props.columns;
  const loading = ref(false);
  const submits = ref(null);
  const setObjId = ref({
    hardwareOptionId: null,
    softwareOptionId: null,
    industryOptionId: null,
  });
  const cascaderValue = ref();
  watch(
    () => props.addres,
    (newValue, oldValue) => {
      console.log('addreswatch', newValue);
      formData.value.country = newValue.country;
      formData.value.city = newValue.mccountries;
      cascaderValue.value = newValue.city;
      // 因为watch被观察的对象只能是getter/effect函数、ref、active对象或者这些类型是数组
      // 所以需要将state.count变成getter函数
    },
  );
  const formData = ref({
    problemDesc: '',
    problemDescImgs: [],
    hardwareOptionId: null,
    softwareOptionId: null,
    industryOptionId: null,
    solution: '',
    solutionImgs: [],
    nickName: '',
    phone: '',
    address: '',
    score: 0,
    scoreReason: '',
  });
  import { useI18n } from 'vue-i18n';
  const { t, locale } = useI18n();
  const showPicker = ref({
    country: false,
    hardwareOptionId: false,
    softwareOptionId: false,
    city: false,
  });
  const columnsCountry = countryList.map((ele) => {
    return { text: ele.chinese, value: locale.value == 'en-us' ? ele.english : ele.chinese };
  });
  const columnsCity = cityList.map((ele) => {
    return {
      text: ele.name,
      value: ele.name,
      children: ele.city.map((element) => {
        return {
          text: element.name,
          value: element.name,
        };
      }),
    };
  });
  // 全部选项选择完毕后，会触发 finish 事件
  const onFinish = ({ selectedOptions }, b) => {
    showPicker.value.city = false;
    console.log('onFinish', cascaderValue.value);
    formData.value.city = selectedOptions.map((option) => option.text).join('/');
  };
  const onConfirm = ({ selectedOptions, selectedValues }, b) => {
    formData.value[b] = selectedValues.join(',');
    setObjId.value[b] = selectedOptions[0].text;
    showPicker.value[b] = false;
  };
  const onSubmit = () => {
    emit('submit', formData.value, setObjId.value);
  };
  const beforeUpload = (file) => {
    console.log('beforeUpload', file);
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      showToast('You can only upload JPG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      showToast('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
  }; //校验图片的格式
  function beforeRead(file) {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'video/mp4' || file.type === 'video/quicktime';
    if (!isJpgOrPng) {
      showToast(t('feedback.fileTips'));
      return false;
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    const isLt50M = file.size / 1024 / 1024 < 50;
    if (!isLt2M && (file.type === 'image/jpeg' || file.type === 'image/png')) {
      showToast(t('feedback.fileTips'));
      return false;
    }
    if (!isLt50M && (file.type === 'video/mp4' || file.type === 'video/quicktime')) {
      showToast(t('feedback.fileTips'));
      return false;
    }
    // if (!/(jpg|jpeg|png|JPG|PNG|mp4|quicktime)/i.test(file.type)) {
    //   showToast(t('feedback.fileTips'));
    //   return false;
    // }
    return true;
  }
  function validator(value, rule) {
    let isOk = Boolean(formData.value[rule.name] || (formData.value[`${rule.name}Imgs`] && formData.value[`${rule.name}Imgs`].length > 0));
    return isOk;
  }
  //照片上传事件方法
  function clzpAfterRead(file) {
    // 上传状态提示开启
    file.status = 'uploading';
    file.message = '上传中...';
    loading.value = true;
    // 创建一个空对象实例
    let formData = new FormData();
    // 调用append()方法添加数据
    formData.append('file', file.file);
    axios({
      url: '/service/sale/upload/file',
      method: 'POST',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    })
      .then((res) => {
        loading.value = false;
        let { data } = res;
        if (data.code == 200) {
          // 上传状态提示关闭
          file.url = data.data;
          file.file = file.file;
          file.content = '';
          file.status = 'done';
          showToast('上传成功！');
          setTimeout(() => {
            console.log('problemDesc', submits.value);
            // submits.value.validate('problemDesc')();
            // submits.value.validate('solution');
          }, 1000);
        }
        console.log('formData.faultImg', formData, file);
      })
      .catch(() => {
        loading.value = false;
      });
  }
</script>

<style lang="scss" scoped>
  .mcSubmit {
    padding-top: 16px;
    .tips {
      font-size: 14px;
      font-family: Source Han Sans CN, Source Han Sans CN;
      font-weight: 400;
      color: #cccccc;
      line-height: 16px;
      margin-top: 15px;
    }
    .required {
      &::before {
        display: inline-block;
        margin-inline-end: 4px;
        color: #ff4d4f;
        font-size: 14px;
        font-family: SimSun, sans-serif;
        line-height: 1;
        content: '*';
        position: absolute;
        left: -11px;
        top: 4.5px;
      }
    }
    .myTitle {
      position: relative;
      margin: 48px 0 15px 0;
      // padding: 0 var(--van-cell-horizontal-padding);
      .number {
        font-size: 16px;
        font-family: Microsoft YaHei, Microsoft YaHei;
        font-weight: bold;
        color: #00b3ec;
      }
      span {
        font-size: 16px;
        font-family: Microsoft YaHei, Microsoft YaHei;
        font-weight: 400;
        color: #333333;
        line-height: 19px;
        margin-right: 7px;
      }
    }
    ::v-deep .uploadercell:after {
      display: none;
    }
    ::v-deep .ratecell:after {
      display: none;
    }
    ::v-deep .van-cell {
      padding: 4px 0px;
    }
    // ::v-deep .van-uploader__upload{
    //   background-color: #fff;
    //   border: 1px solid #e4e4e5;
    //   border-radius: 5px;
    // }
    // .zdycell {
    //   border: 1px solid #e4e4e5;
    //   border-radius: 5px;
    // }
    .uploadercell {
      padding: 20px 0 0 0;
    }
  }
</style>
