<template>
  <div class="app-container">
    <el-form validate-on-rule-change :rules="rules" ref="form" :model="form" label-width="140px">
      <el-form-item label="信息模板" prop="questionId">
        <el-select @change="selectQuestion" v-model="form.questionId" placeholder="请选择问答">
          <el-option v-for="dict in questionOptions" :key="dict.dictValue" :label="dict.dictLabel"
                     :value="parseInt(dict.dictValue)" />
        </el-select>
      </el-form-item>

      <!-- 动态渲染问题区域 -->
      <div v-if="form.answers && form.answers.length > 0">
        <div style="margin-bottom: 20px;margin-top: 20px;" v-for="(answer, index) in form.answers" :key="index">
          <div style="margin-bottom: 20px;margin-top: 20px;">
            <span style="font-size: 15px;font-weight: bold; margin-left: 31px">{{ answer.title }}</span>
          </div>
          <div style="margin-left: 31px;">
            <el-checkbox-group v-model="answer.value" size="mini">
              <el-checkbox v-for="option in answer.options" :key="option.value" :label="option.value">
                {{ option.name }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
      </div>

      <el-form-item label="用户姓名" prop="userName">
        <el-input v-model="form.userName" placeholder="请输入用户姓名"></el-input>
      </el-form-item>
      <el-form-item label="用户手机号后四位" prop="userPhoneFour">
        <el-input v-model="form.userPhoneFour" placeholder="请输入手机号后四位"></el-input>
      </el-form-item>
      <el-form-item label="用户性别" prop="sex">
        <el-select v-model="form.sex" placeholder="请选择用户性别">
          <el-option label="男" :value="1" />
          <el-option label="女" :value="0" />
        </el-select>
      </el-form-item>

      <el-form-item label="过敏情况" prop="allergy">
        <el-input type="textarea" :rows="2" placeholder="请输入过敏情况" v-model="form.allergy">
        </el-input>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input type="textarea" :rows="2" placeholder="请输入备注" v-model="form.remark">
        </el-input>
      </el-form-item>
      <el-form-item v-if="form.questionId" label="是否关联产品疗法" prop="isPackage">
        <el-radio-group v-model="form.isPackage" @change="handleIsPackageChange">
          <el-radio :label="0">否</el-radio>
          <el-radio :label="1">是</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="form.isPackage == 1" label="产品疗法" prop="packageId">
        <el-select filterable v-model="form.packageId" placeholder="请选择产品疗法">
          <el-option v-for="dict in privatePackageOptions" :key="dict.dictValue" :label="dict.dictLabel"
                     :value="parseInt(dict.dictValue)" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="form.packageId && form.isPackage && form.isPackage == 1" label="支付类型" prop="payType">
        <el-radio-group v-model="form.payType">
          <el-radio :label="1">全款</el-radio>
          <el-radio :label="2">物流代收</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="form.packageId && form.payType == 2 && form.isPackage && form.isPackage == 1"
                    label="预付金额" prop="amount">
        <el-input v-model="form.amount" placeholder="请输入物流代收金额" type="number" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </div>

    <el-dialog :title="collectionForm.title" v-if="collectionForm.open" :visible.sync="collectionForm.open"
               width="450px" append-to-body>
      <div style="padding-bottom:15px;">
        <img :src="codeImage" width="400px">
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="downloadImage(codeImage, collectionForm.name + '.png')">下载二维码</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { questionOptions, getAnswer } from "@/api/hisStore/answer";
import { allPrivatePackage } from "@/api/store/package";
import { getInfo, addCollection, updateCollection, getWxaCodeCollectionUnLimit } from "@/api/hisStore/collection";

export default {
  name: "collection",
  components: {},
  data() {
    // 自定义姓名校验规则
    const validateName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入用户姓名'));
      }
      if (value.length < 1 || value.length > 20) {
        return callback(new Error('姓名长度在 1 到 20 个字符'));
      }
      // 校验不能包含数字
      const numberRegex = /[0-9]/;
      if (numberRegex.test(value)) {
        return callback(new Error('姓名不能包含数字'));
      }
      // 可选：校验只能包含中文、英文和空格
      const nameRegex = /^[\u4e00-\u9fa5a-zA-Z\s]+$/;
      if (!nameRegex.test(value)) {
        return callback(new Error('姓名只能包含中文、英文和空格'));
      }
      callback();
    };
    return {
      form: {
        id: null,
        questionId: null,
        packageId: null,
        payType: null,
        amount: null,
        isPackage: null,
        answers: [],
        userName: '',
        userPhoneFour: '',
        sex: null,
        allergy: '',
        remark: ''
      },
      userId: null,
      questionOptions: [],
      privatePackageOptions: [],
      collectionForm: {
        open: false,
        title: "用户信息采集分享",
        name: null,
      },
      codeImage: null,

      rules: {
        questionId: [
          { required: true, message: '请选择信息模板', trigger: 'change' }
        ],
        packageId: [
          { required: true, message: '请选择套餐包', trigger: 'change' }
        ],
        isPackage: [
          { required: true, message: '请选择是否关联套餐包', trigger: 'change' }
        ],
        payType: [
          { required: true, message: '请选择支付类型', trigger: 'change' }
        ],
        amount: [
          { required: true, message: '请填写物流代收金额', trigger: 'blur' }
        ],
        userName: [
          { required: true, validator: validateName, trigger: 'blur' }
        ],
        userPhoneFour: [
          { required: true, message: '请输入手机号后四位', trigger: 'blur' },
          { pattern: /^\d{4}$/, message: '请输入正确的4位数字', trigger: 'blur' }
        ],
        sex: [
          { required: true, message: '请选择用户性别', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              if (value !== 0 && value !== 1) {
                callback(new Error('性别只能为男(1)或女(0)'));
              } else {
                callback();
              }
            },
            trigger: 'change'
          }
        ]
      }
    };
  },
  created() {
    this.getQuestionOptions();
    this.getAllPrivatePackge();
  },
  methods: {
    handleIsPackageChange(value) {
      if (value === 0) {
        this.form.packageId = null;
        this.form.payType = null;
        this.form.amount = null;
        this.$nextTick(() => {
          this.$refs.form.clearValidate(['packageId', 'payType', 'amount']);
        });
      }
    },
    downloadImage(imageSrc, fileName) {
      const link = document.createElement('a');
      link.href = imageSrc;
      link.download = fileName || '付款二维码.png';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    handleShare(id) {
      let loadingRock = this.$loading({
        lock: true,
        text: '生成二维码中~~请不要刷新页面！！',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      getWxaCodeCollectionUnLimit(id).then(response => {
        this.codeImage = response.url
        this.collectionForm.open = true;
        this.collectionForm.name = id;
        loadingRock.close();
      }).finally(res => {
        loadingRock.close();
      })
    },
    getQuestionOptions() {
      questionOptions().then(response => {
        this.questionOptions = response.rows;
      })
    },
    getAllPrivatePackge() {
      allPrivatePackage().then(res => {
        this.privatePackageOptions = res.rows;
      })
    },
    getCollectionInfo(userId) {
      this.userId = userId;
      getInfo({ userId }).then(res => {
        console.log('获取用户采集信息:', res.data); // 调试日志
        if (res.data) {
          this.processFormData(res.data);
        } else {
          this.resetFormData();
        }
      }).catch(error => {
        console.error('获取用户采集信息失败:', error);
        this.resetFormData();
      });
    },

    processFormData(data) {
      // 处理 answers 数据，确保 value 是数组格式
      let processedAnswers = [];
      if (data.answers && Array.isArray(data.answers)) {
        processedAnswers = data.answers.map(answer => ({
          ...answer,
          value: Array.isArray(answer.value) ? answer.value : []
        }));
      }

      this.form = {
        ...this.form,
        id: data.id || null,
        questionId: data.questionId || null,
        packageId: data.packageId || null,
        payType: data.payType || null,
        amount: data.amount || null,
        isPackage: data.isPackage ?? null,
        answers: processedAnswers,
        userName: data.userName || '',
        userPhoneFour: data.userPhoneFour || '',
        sex: data.sex ?? null,
        allergy: data.allergy || '',
        remark: data.remark || ''
      };

      console.log('处理后的表单数据:', this.form); // 调试日志
    },

    resetFormData() {
      this.form = {
        ...this.form,
        id: null,
        questionId: null,
        packageId: null,
        payType: null,
        amount: null,
        isPackage: null,
        answers: [],
        userName: '',
        userPhoneFour: '',
        sex: null,
        allergy: '',
        remark: ''
      };
    },

    //选择问答模板
    selectQuestion(val) {
      console.log('选择模板:', val); // 调试日志

      // 保留用户已填写的基础信息
      const preservedFields = {
        userName: this.form.userName,
        userPhoneFour: this.form.userPhoneFour,
        sex: this.form.sex,
        allergy: this.form.allergy,
        remark: this.form.remark,
      };

      // 先重置表单
      this.form = {
        ...preservedFields,
        questionId: val,
        answers: [],
        isPackage: null,
        packageId: null,
        payType: null,
        amount: null,
        id: null
      };

      // 查询该用户+该模板下是否有历史采集记录
      if (this.userId && val) {
        getInfo({ userId: this.userId, questionId: val }).then(res => {
          console.log('查询历史记录:', res.data); // 调试日志
          if (res.data) {
            this.processFormData(res.data);
          }
        }).catch(error => {
          console.error('查询历史记录失败:', error);
        });
      }
    },

    submitForm() {
      console.log('提交表单数据:', this.form); // 调试日志
      this.form.userId = this.userId;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCollection(this.form).then(res => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.$parent.$parent.closeCollection();
              this.$refs['form'].resetFields();
              this.handleShare(res.data);
            })
          } else {
            addCollection(this.form).then(res => {
              this.msgSuccess("添加成功");
              this.open = false;
              this.$parent.$parent.closeCollection();
              this.$refs['form'].resetFields();
              this.handleShare(res.data);
            })
          }
        }
      });
    },
    cancel() {
      // 取消逻辑
    },
  },
};
</script>
