import { connect } from 'herculex';
import { toast } from '../../utils/jsapi';
import request from '../../utils/request';
import { saveFormDataUrl, getFormConfigDetailUrl } from '../../utils/constants';

Component(connect({
})({
  data: {
    defaultConfig: {
      regionPicker: {
        showAutoLocate: true,
      },
      datePicker: {
        format: 'yyyy-MM-dd',
        currentDate: '',
        startDate: '',
        endDate: '',
        showIcon: true,
      },
      textarea: {
        showCount: false,
        maxlength: 140,
      },
      optionsSelect: {
        optionsOne: [],
        optionsTwo: [],
      },
      multiLevelSelect: {
        multiLevelSelectItems: [],
      },
    },
    //
    cardModel: false,
    isValidate: true,
    editable: true,
    title: '',
    backgroundUrl: '',
    showButton: false,
    formFieldList: [],
    formValue: {},
  },
  props: {
    componentData: {},
  },

  didMount() {
    this.getFormConfigDetail();
  },

  methods: {
    onChange(d) {
      this.setData({
        formValue: d,
      });
    },

    // 加载表单配置
    async getFormConfigDetail() {
      const { componentExtInfo: { formUuid } } = this.props.componentData;
      const [err, response] = await request({
        url: getFormConfigDetailUrl,
        method: 'get',
        data: { uuid: formUuid },
      });
      if (err) throw err;
      // 设置默认值
      const formValue = {}; const
        configList = [];
      response.formFieldList.forEach((item) => {
        if (!item.hide) {
          configList.push(this.getComponentConfig(item));
          formValue[item.fieldKey] = item.fieldValue;
          // formValue[item.fieldName] = item.fieldValue || '';
        }
      });
      this.setData({
        ...response,
        title: configList.length > 0 ? response.formName : '',
        showButton: response.showButton,
        isCard: response.cardModel || false,
        formFieldList: configList,
        formValue,
      });
    },

    getFormValue() {
      const formValue = {};
      for (const item of this.data.formFieldList) {
        const value = this.data.formValue[item.key];
        formValue[item.key] = '';
        if (!value) continue;
        if (item.mode === 'optionsSelect') {
          formValue[item.key] = value.selectedOneOption + (value.selectedOneOption || '');
        } else if (item.mode === 'regionPicker' || item.mode === 'dynamicMultiLevelPicker' || item.mode === 'multiLevelSelect') {
          value.forEach((v) => {
            formValue[item.key] += v.name;
          });
        } else {
          formValue[item.key] = value;
        }
      }
      return formValue;
    },

    // 提交表单
    async onSumbit() {
      let formValidate = true;
      for (const item of this.data.formFieldList) {
        if (item.require && !this.data.formValue[item.key]) {
          formValidate = false;
        }
      }
      this.setData({
        isValidate: formValidate,
      });
      if (!formValidate) return;
      //
      my.showLoading({ content: '正在提交' });
      const { componentExtInfo: { formUuid } } = this.props.componentData;
      const formValue = this.getFormValue();
      const [err, response] = await request({
        url: saveFormDataUrl,
        header: { 'content-type': 'application/json' },
        data: {
          formUuid,
          ...formValue,
        },
      });
      my.hideLoading();
      if (err) toast(err.msg);
      if (response) toast('提交成功');
    },

    getComponentConfig(option) {
      const config = {
        ...this.data.defaultConfig[option.fieldMode],
        label: option.label,
        key: option.fieldKey,
        mode: option.fieldMode,
        type: option.fieldType || 'string',
        require: option.require,
        allowClear: option.allowClear,
        tips: option.tips || '',
        placeholder: option.placeholder || '',
        disabled: !option.editable || '',
        password: option.hide || false,
      };
      if (option.fieldMode === 'optionsSelect' && option.dataSource) {
        config.optionsOne = option.dataSource.split(',') || [];
      } else if (option.fieldMode === 'multiLevelSelect' && option.dataSource) {
        config.multiLevelSelectItems = this.checkJson(option.dataSource) ? JSON.parse(option.dataSource) : [];
      }
      return config;
    },
    checkJson(str) {
      if (typeof str === 'string') {
        try {
          const obj = JSON.parse(str);
          if (typeof obj === 'object' && obj) {
            return true;
          } else {
            return false;
          }
        } catch (e) {
          console.log(`error：${str}!!!${e}`);
          return false;
        }
      }
      return false;
    },
  },
}));
