<template>
  <view class="inspectionValue">
    <scroll-view scroll-y class="body">
      <uni-forms ref="baseForm" :model="formValues" :rules="rules" class="form" label-position="top">
        <template v-for="(item, index) of baseFormData" :key="index">
          <!-- 下拉 -->
          <uni-forms-item v-if="item.type === '1'" class="formItem" :required="item.required" :name="item.key">
            <template v-slot:label>
              <view class="customLabelWrap">
                <text class="customLabel">{{item.name}}</text><text v-if="item.isException" class="customLabel red">&nbsp;异</text>
              </view>
            </template>
            <uni-data-picker :placeholder="'请选择' + item.name" :popup-title="'请选择' + item.name" :localdata="item.list" v-model="formValues[item.key]" @change="changeForm()">
            </uni-data-picker>
          </uni-forms-item>
          <!-- 单选 -->
          <uni-forms-item v-if="item.type === '2'" class="formItem" :required="item.required" :name="item.key">
            <template v-slot:label>
              <view class="customLabelWrap">
                <text class="customLabel">{{item.name}}</text><text v-if="item.isException" class="customLabel red">&nbsp;异</text>
              </view>
            </template>
            <uni-data-checkbox v-model="formValues[item.key]" @change="changeForm()" :localdata="item.list" />
          </uni-forms-item>
          <!-- 多选 -->
          <uni-forms-item v-if="item.type === '3'" class="formItem" :required="item.required" :name="item.key">
            <template v-slot:label>
              <view class="customLabelWrap">
                <text class="customLabel">{{item.name}}</text><text v-if="item.isException" class="customLabel red">&nbsp;异</text>
              </view>
            </template>
            <uni-data-checkbox v-model="formValues[item.key]" @change="changeForm()" multiple :localdata="item.list" />
          </uni-forms-item>
          <!-- 数字 -->
          <uni-forms-item v-if="item.type === '4'" class="formItem" :required="item.required" :name="item.key">
            <template v-slot:label>
              <view class="customLabelWrap">
                <text class="customLabel">{{item.name}}</text><text v-if="item.isException" class="customLabel red">&nbsp;异</text>
              </view>
            </template>
            <uni-number-box v-model="formValues[item.key]" @change="changeForm()" :min="-9999" :max="9999" :placeholder="'请输入' + item.name"></uni-number-box>
          </uni-forms-item>
          <!-- 单行 -->
          <uni-forms-item v-if="item.type === '5' && item.isException" class="formItem" :label="item.name" :required="item.required" :name="item.key">
            <uni-easyinput v-model="formValues[item.key]" :placeholder="'请输入' + item.name" />
          </uni-forms-item>
          <!-- 多行 -->
          <uni-forms-item v-if="item.type === '6' && item.isException" class="formItem" :label="item.name" :required="item.required" :name="item.key">
            <uni-easyinput type="textarea" v-model="formValues[item.key]" :placeholder="'请输入' + item.name" />
          </uni-forms-item>
          <!-- 图片上传 -->
          <uni-forms-item v-if="item.type === '7' && item.isException" class="formItem" :label="item.name" :required="item.required" :name="item.key">
            <DsFilePicker v-model="formValues[item.key]"></DsFilePicker>
          </uni-forms-item>
          <!-- 分割线 -->
          <view class="detail_head" v-if="item.type === '8'">
            <text class="title">{{ item.name }}</text>
          </view>
        </template>
      </uni-forms>
    </scroll-view>
    <view class="foot_common_btns">
      <button @click="goBack" type="default" class="cancelButton btn">返回</button>
      <button @click="submit" type="default" class="primaryButton btn">保存</button>
    </view>
  </view>
</template>

<script setup>
  import fromPairs from 'lodash-es/fromPairs'
  import keyBy from 'lodash-es/keyBy'
  import DsFilePicker from '@/components/DsFilePicker.vue';
  import { ref, reactive } from 'vue'
  import { onLoad } from '@dcloudio/uni-app'
  import { api_addModel } from "@/http/api.js"
  import { defaultColor } from '@/static/js/theme.js'
  import { useSetTitle } from '@/share/useSetTitle.js'
  import { useMakePhoneCall } from '@/share/useMakePhoneCall.js'
  import { useGoBack } from '@/share/useGoBack.js'
  import { useLoginUserStore } from '@/stores/loginUser'
  import { useInspectionValueStore } from '@/stores/inspectionValue'
import { forIn } from 'lodash-es';

  useSetTitle();
  const loginUserStore = useLoginUserStore();
  const { goBack }  = useGoBack();
  const inspectionValueStore = useInspectionValueStore();

  // 主题颜色
  const primaryColor = ref(defaultColor)

  // 所有页码数据
  const formPageList = reactive([]);

  // 表单
  const baseForm = ref()

  const inspectionExecuteId = ref()

  // 数据-原始
  const dataInfo = reactive({})

  // 数据-检验
  const rules = reactive({})

  // 数据-填写值
  const formValues = reactive({})

  // 表单数据-渲染
  // 下拉框	1
  // 单选	2
  // 多选	3
  // 数值	4
  // 单行文本	5
  // 多行文本	6
  // 照片上传	7
  // 分割线	8
  const baseFormData = reactive([
    // { type: 1, name: '', value: '', list: [], required: false, checkType: 0, valueMin: '', valueMax: '', },
    // { type: 2, name: '', value: '', list: [], required: false, checkType: 0, valueMin: '', valueMax: '', },
    // { type: 3, name: '', value: [], list: [], required: false, checkType: 0, valueMin: '', valueMax: '', },
    // { type: 4, name: '', value: '', list: [], required: false, checkType: 0, valueMin: '', valueMax: '', },
    // { type: 5, name: '', value: '', list: [], required: false, checkType: 0, valueMin: '', valueMax: '', },
    // { type: 6, name: '', value: '', list: [], required: false, checkType: 0, valueMin: '', valueMax: '', },
    // { type: 7, name: '', value: [], list: [], required: false, checkType: 0, valueMin: '', valueMax: '', },
  ])

  // 修改
  function changeForm(){
    handleData(true);
  }

  // 保存
  function submit(){
    baseForm.value.validate().then(res => {
      console.log('success', res);
      uni.showLoading({
        title: "加载中",
        mask: true,
      });
      console.log(formValues);
      let postData = {
        account: loginUserStore.loginUser.user.account,
        valuesList: [],
      };
      // baseFormData
      for(let key in formValues){
        let obj = baseFormData.find(v => v.key === key);
        if(!((obj.type === '5' && !obj.isException) || (obj.type === '6' && !obj.isException) || (obj.type === '7' && !obj.isException))){
          let name = obj.name;
          let itemId = obj.id;
          let _formPageList = dataInfo.inspectionFormDTO?.formPageList || [];
          _formPageList = _formPageList.map(v => v.formItemList).flat();
          let formItem = _formPageList.find(v => v.id === itemId);
          postData.valuesList.push({
            taskId: inspectionExecuteId.value,
            nodeId: dataInfo.id,
            formId: dataInfo.inspectionFormDTO.id,
            itemId: formItem.id,
            pageId: formItem.pageId,
            orders: formItem.orders,
            name,
            valuex: (formItem.type.value === '1' || formItem.type.value === '2' || formItem.type.value === '3') ? '' : formValues[key].toString(),
            configIds: (formItem.type.value === '1' || formItem.type.value === '2' || formItem.type.value === '3') ? formValues[key].toString() : undefined,
            hosId: dataInfo.inspectionFormDTO.hosId,
          })
        }
      }
      console.log(postData);
      api_addModel(postData).then((res) => {
        uni.hideLoading();
        if (res.status == 200) {
          inspectionValueStore.clearInspectionValueData();
          uni.reLaunch({
            url: `/pages/inspection/inspectionExecute/inspectionExecute`
          })
        } else {
          uni.showToast({
            icon: 'none',
            title: res.msg || '请求数据失败！'
          });
        }
      });
    }).catch(err => {
      console.log('err', err);
    })
  }

  // 处理数据
  function handleData(isException = false){
    // 目前只取第一页
    let firstPage = formPageList[0]?.formItemList || [];

    firstPage = firstPage.filter( v => v.display === 1);

    firstPage = firstPage.map((v, i) => {
      let value = '';
      v.formItemConfigList = v.formItemConfigList || [];

      // value
      if(v.type.value === '3'){
        // 多选
        let arr = v.formItemConfigList.filter(v => v.checkDefault === 1);
        value = arr.length ? arr.map(v => v.id) : [];
        console.log('多选', value)
      } else if(v.type.value === '7'){
        // 图片
        value = [];
      } else if(v.type.value === '1' || v.type.value === '2') {
        // 单选或下拉
        let defaultValue = v.formItemConfigList.find(v => v.checkDefault === 1);
        value = defaultValue ? defaultValue.id : '';
        console.log('单选或下拉', value)
      } else{
        // 其他
        value = v.defaultValue;
      }

      return {
        id: v.id,
        key: `field${i}`,
        type: v.type.value,
        name: v.name,
        value: isException ? formValues[`field${i}`] : value,
        list: v.formItemConfigList ? v.formItemConfigList.map(v => ({text: v.name, value: v.id, checkException: v.checkException, uncheckException: v.uncheckException})) : [],
        required: v.required === 1,
        checkType: v.checkType,
        showError: v.showError,
        orders: v.orders,
        valueMin: v.checkType === 2 ? v.valueLow : ( v.checkType === 1 ? (v.valuex - v.valueGap) : undefined),
        valueMax: v.checkType === 2 ? v.valueUp : ( v.checkType === 1 ? (v.valuex + v.valueGap) : undefined),
      }
    });

    let firstPageBottom = firstPage.filter(v => v.type === '5' || v.type === '6');
    firstPage = firstPage.filter(v => v.type !== '5' && v.type !== '6' && v.type !== '7');

    // 其他项
    if(isException){
      firstPage.forEach(v => {
        // 下拉,单选
        if(v.type === '1' || v.type === '2'){
          let obj = v.list.find(vv => formValues[v.key] === vv.value);
          v.isException = obj ? obj.checkException === 1 : false;
        } else if(v.type === '3'){
          // 多选
          v.isException = v.list.some(vv => {
            if(formValues[v.key].includes(vv.value)){
              return vv.checkException === 1;
            }else{
              return false;
            }
          })
        } else if(v.type === '4'){
          v.isException = (v.value < v.valueMin) || (v.value > v.valueMax);
        }
      })
    }else{
      firstPage.forEach(v => {
        if(v.type === '1' || v.type === '2'){
          // 下拉,单选
          let obj = v.list.find(vv => v.value === vv.value);
          v.isException = obj ? obj.checkException === 1 : false;
        } else if(v.type === '3'){
          // 多选
          v.isException = v.list.some(vv => {
            if(v.value.includes(vv.value)){
              return vv.checkException === 1;
            }else{
              return false;
            }
          })
        } else if(v.type === '4'){
          // 数值
          v.isException = (formValues[v.key] < v.valueMin) || (formValues[v.key] > v.valueMax);
        }
      })
    }

    // 单行|多行|图片上传
    let someIsException = firstPage.filter(v => v.type !== '8').some(v => v.isException);
    console.log('someIsException=>', someIsException)
    firstPageBottom.forEach(v => {
      console.log('v.showError=>', v.showError)
      v.isException = (v.showError === 1 && someIsException) || v.showError === 0;
    })

    firstPage = firstPage.concat(firstPageBottom).sort((a, b) => a.orders - b.orders);
    console.log('firstPage=>', firstPage);

    Object.assign(baseFormData, firstPage);
    console.log('baseFormData=>', baseFormData);

    Object.assign(formValues, fromPairs(firstPage.filter(v => v.type !== '8').map(v => ([v.key, v.value]))));
    console.log('formValues=>', formValues);

    let rulesObj = keyBy(firstPage.filter(v => v.type !== '8'), 'key');
    console.log(rulesObj)

    for(let key in rulesObj){
      rulesObj[key] = {
        rules: [
          { required: rulesObj[key].required, errorMessage: `${rulesObj[key].name}不能为空` }
        ]
      }
    }
    Object.assign(rules, rulesObj);
    console.log('rules=>', rules);
  }

  onLoad((option) => {
    inspectionExecuteId.value = +option.inspectionExecuteId;
    // 巡检项
    if(inspectionValueStore.inspectionValue.data){
      Object.assign(dataInfo, inspectionValueStore.inspectionValue.data);
      Object.assign(formPageList, dataInfo.inspectionFormDTO?.formPageList || []);
      handleData()
    }
  })
</script>

<style lang="scss" scoped>
.inspectionValue{
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .body{
    box-sizing: border-box;
    flex: 1;
    min-height: 0;
    padding-bottom: 24rpx;
    .formItem{
      padding: 24rpx 24rpx 0;
      margin-bottom: 0;
    }
    ::v-deep .uni-forms-item__label{
      width: auto!important;
    }
    .detail_head{
      padding: 24rpx;
      border-top: 1rpx solid #D2D2D2;
      border-bottom: 1rpx solid #D2D2D2;
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 24rpx;
      &:first-of-type{
        border-top: none;
        margin-top: 0;
      }
      .title{
        font-size: 26rpx;
        color: $uni-primary;
        padding-left: 18rpx;
        position: relative;
        &:before{
          content: '';
          width: 8rpx;
          height: 25rpx;
          background-color: $uni-primary;
          position: absolute;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
        }
      }
    }
  }
}
</style>
