<template>
  <j-modal
    :confirmLoading="confirmLoading"
    :title="title"
    :width="1200"
    :visible="visible"
    :maskClosable="false"
    switchFullscreen
    @ok="handleOk"
    :okButtonProps="{ class:{'jee-hidden': disableSubmit} }"
    @cancel="handleCancel">
    <a-spin :spinning="confirmLoading">
      <j-form-container :disabled="formDisabled">
        <!-- 主表单区域 -->
        <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
          <a-row>
            <a-col :span="12">
              <a-form-model-item label="姓名" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
                <a-input v-model="model.name" placeholder="请输入姓名"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="性别" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="gender">
                <j-dict-select-tag v-model="model.gender" dictCode="sex" placeholder="请选择性别" />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-model-item label="身份证号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="identity">
                <a-input v-model="model.identity" placeholder="请输入身份证号"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="年龄" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="age">
                <a-input v-model="model.age" disabled></a-input>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-model-item label="是否失学" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="school">
                <j-dict-select-tag v-model="model.school" dictCode="school_status" placeholder="请选择是否失学" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="家庭住址" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="address">
                <a-textarea v-model="model.address" placeholder="请输入家庭住址" :rows="1" ></a-textarea>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-model-item label="监护人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="guardian">
                <a-input v-model="model.guardian" placeholder="请输入监护人"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="监护人关系" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="relation">
                <a-input v-model="model.relation" placeholder="请输入监护人关系"></a-input>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-model-item label="重点关注原因" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="reason">
                <a-textarea v-model="model.reason" placeholder="请输入重点关注原因"></a-textarea>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
                <a-textarea v-model="model.remark" placeholder="请输入备注"></a-textarea>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </j-form-container>
      <!-- 子表单区域 -->
      <a-tabs activeKey="1" style="margin-top: -20px">
        <a-tab-pane tab="家庭成员" key="1" :forceRender="true">
          <j-editable-table
            ref="editableTable"
            :loading="familyLoading"
            sticky :columns="columns"
            :dataSource="dataSource"
            :maxHeight="190"
            :rowNumber="true"
            :rowSelection="true"
            :actionButton="true" />

        </a-tab-pane>

      </a-tabs>
    </a-spin>
  </j-modal>
</template>

<script>
import { getAction, httpAction } from '@/api/manage'
import { FormTypes, VALIDATE_NO_PASSED, getRefPromise, validateFormModelAndTables } from '@/utils/JEditableTableUtil'
import JEditableTable from '@/components/jeecg/JEditableTable'
import JDate from '@/components/jeecg/JDate'

export default {
  name: 'MinorModal',
  components: {
    JEditableTable, JDate
  },
  data() {
    return {
      confirmLoading: false,
      title: '',
      width: 800,
      visible: false,
      disableSubmit: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      labelCol2: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol2: {
        xs: { span: 24 },
        sm: { span: 20 }
      },
      validatorRules: {
        name:[ { required: true, message: '请输入姓名' },],
        gender:[ { required: true, message: '请选择性别' },],
        identity:[  {required: true,validator:this.validateIdCard}],
        relation:[ { required: true, message: '请输入监护人关系' },],
        guardian:[ { required: true, message: '请输入监护人' },],
      },
      url: {
        add: '/sys/minor/add',
        edit: '/sys/minor/edit',
        queryById: '/sys/minor/queryById',
        familys: '/sys/minor/queryFamilyByMainId'
      },
      familyLoading: false,
      dataSource: [],
      columns: [
        {
          title: '户号',
          key: 'householdNum',
          width: '250px',
          type: FormTypes.input,
          fixed: 'left',
          defaultValue: '',
          placeholder: '请输入${title}',
          validateRules: [{ required: true, message: '${title}不能为空' }]
        },
        {
          title: '姓名',
          key: 'name',
          width: '180px',
          fixed: 'left',
          type: FormTypes.input,
          defaultValue: '',
          placeholder: '请输入${title}',
          validateRules: [{ required: true, message: '${title}不能为空' }]
        },
        {
          title: '身份证号',
          key: 'identity',
          width: '200px',
          type: FormTypes.input,
          defaultValue: '',
          placeholder: '请输入${title}',
          validateRules: [{
            pattern: '/(^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)|(^[1-9]\\d{7}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}$)/',
            message: '${title}格式不正确'
          }]
        },
        {
          title: '婚姻状况',
          key: 'marital',
          width: '200px',
          type: FormTypes.select,
          options: [],
          dictCode: 'marital_status',
          placeholder: '请选择${title}',
          validateRules: [{ required: true, message: '${title}不能为空' }]
        },
        {
          title: '是否犯罪',
          key: 'crime',
          width: '200px',
          type: FormTypes.select,
          options: [],
          dictCode: 'is_crime',
          placeholder: '请选择${title}',
          validateRules: [{ required: true, message: '${title}不能为空' }]
        },
        {
          title: '犯罪原因',
          key: 'reason',
          width: '250px',
          type: FormTypes.input_pop,
          defaultValue: '',
          placeholder: '请输入${title}',
          validateRules: [{ required: true, message: '${title}不能为空' }]
        },
        {
          title: '其他参考信息',
          key: 'other',
          width: '250px',
          type: FormTypes.input_pop,
          defaultValue: '',
          placeholder: '请输入${title}',
          validateRules: [{ required: true, message: '${title}不能为空' }]
        }
      ]
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    }
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
  },
  methods: {
    validateIdCard(rule,value,callback){
      console.log(value)
      if(undefined==value || null==value || ''==value){
        callback("请输入正确的公民身份号码!");
      }else if ( !value || new RegExp(/(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{7}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}$)/).test(value)){
        callback();
      }else{
        callback("请输入正确的公民身份号码!");
      }
    },
    // 获取所有的editableTable实例
    getAllTable() {
      return Promise.all([
        getRefPromise(this, 'editableTable')
      ])
    },

    add() {
      // 默认新增一条数据
      this.getAllTable().then(editableTables => {
        editableTables[0].add()
      })

      this.edit({})
    },
    edit(record) {
      this.model = Object.assign({}, record)
      this.visible = true
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestTableData(this.url.familys, params)
      }
    },
    /** 查询某个tab的数据 */
    requestTableData(url, params) {
      this.familyLoading = true
      getAction(url, params).then(res => {
        this.dataSource = res.result || []
      }).finally(() => {
        this.familyLoading = false
      })
    },
    handleCancel() {
      this.close()
    },
    close() {
      this.visible = false
      this.getAllTable().then(editableTables => {
        editableTables[0].initialize()
      })
      this.$emit('close')
      this.$refs.form.resetFields()
    },
    handleOk() {
      this.validateFields()
    },
    /** 触发表单验证 */
    validateFields() {
      this.getAllTable().then(tables => {
        /** 一次性验证主表和所有的次表 */
        return validateFormModelAndTables(this.$refs.form, this.model, tables)
      }).then(allValues => {
        let formData = this.classifyIntoFormData(allValues)
        // 发起请求
        return this.requestAddOrEdit(formData)
      }).catch(e => {
        if (e.error === VALIDATE_NO_PASSED) {
          // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
          this.activeKey = e.index == null ? this.activeKey : (e.index + 1).toString()
        } else {
          console.error(e)
        }
      })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let MinorPage = Object.assign(this.model, allValues.formValue)
      return {
        ...MinorPage, // 展开
        familyList: allValues.tablesValue[0].values
      }
    },
    /** 发起新增或修改的请求 */
    requestAddOrEdit(formData) {
      let url = this.url.add, method = 'post'
      if (this.model.id) {
        url = this.url.edit
        method = 'put'
      }
      this.confirmLoading = true
      httpAction(url, formData, method).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.$emit('ok')
          this.close()
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.confirmLoading = false
      })
    }
  }
}
</script>

<style scoped>

</style>