<template>
  <div>
    <zj-form-container ref="formRef" :formData="formData" :formRules="formRules">
      <zj-form-module title="保险基础信息" label-width="110px" :formData="formData" :formItems="formItems" :column="3">
      </zj-form-module>
      <zj-form-module title="保单内容" label-width="100px" :formData="formData" :formItems="formItems2" :column="3">
      </zj-form-module>
      <zj-form-module title="网点信息" label-width="0px" :formData="formData" :formItems="items2"> </zj-form-module>
    </zj-form-container>
    <div v-if="type === 0 || type === 1" style="text-align: right">
      <el-button size="mini" @click="submit">提交</el-button>
      <el-button size="mini" @click="reset">重置</el-button>
    </div>
  </div>
</template>

<script>
import { insureDetail, insureAdd, insureUpdate } from '@/api/InsuranceManagement.js'
import { dateFormat } from '@/utils/util'
import pagingTransfer from '@/components/paging-transfer.vue'
import { EventBus } from '@/utils/eventBus'
import { required } from '@/components/template/rules_verify.js'
import { getWebsit } from '@/api/customerManagement.js'
export default {
  props: {
    type: {
      type: Number,
      default: null
    },
    item: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      disabled: this.type === 2,
      // 表单数据
      formData: {
        policyName: '',
        policyNumber: '',
        policyPrice: '',
        startTime: '',
        endTime: '',
        policyStartTime: '',
        isBuy: 'YES',
        company: '',
        text: '',
        month1: '',
        month2: '',
        month3: '',
        month4: '',
        month5: '',
        month6: '',
        month7: '',
        month8: '',
        month9: '',
        month10: '',
        month11: '',
        month12: '',
        policyRanges: [{ rangeName: '', rangeText: '' }],
        policyWebsits: [],
        type: ''
      },
      formRules: {
        text: [{ required: true, message: '请输入', trigger: 'blur' }],
        policyName: [{ required: true, message: '请输入', trigger: 'blur' }],
        policyNumber: [{ required: true, message: '请输入', trigger: 'blur' }],
        policyPrice: [{ required: true, message: '请输入', trigger: 'blur' }],
        startTime: [{ required: true, message: '请输入', trigger: 'blur' }],
        endTime: [{ required: true, message: '请输入', trigger: 'blur' }],
        policyStartTime: [{ required: true, message: '请输入', trigger: 'blur' }],
        company: [{ required: true, message: '请输入', trigger: 'blur' }],
        month1: [
          { required: true, message: '全部必填', trigger: 'blur' },
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value === '') {
                callback(new Error('请输入'))
              } else if (value > 100 || value < 0) {
                callback(new Error('百分比必须为0到100的数值'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      },
      monthKeys: [
        'month1',
        'month2',
        'month3',
        'month4',
        'month5',
        'month6',
        'month7',
        'month8',
        'month9',
        'month10',
        'month11',
        'month12'
      ],
      formInline: {
        websitId: '',
        websitName: ''
      },
      itemsList: []
    }
  },
  computed: {
    formItems() {
      return [
        {
          name: 'el-input',
          attributes: { disabled: this.disabled },
          formItemAttributes: { label: '保单名称', prop: 'policyName' }
        },
        {
          name: 'el-input',
          attributes: { disabled: this.disabled },
          formItemAttributes: { label: '保单编号', prop: 'policyNumber' }
        },
        {
          name: 'el-input',
          attributes: { disabled: this.disabled },
          formItemAttributes: { label: '保单金额', prop: 'policyPrice' }
        },
        {
          name: 'el-date-picker',
          attributes: { disabled: this.disabled, type: 'date', style: { width: '100%' } },
          formItemAttributes: { label: '生效时间', prop: 'startTime' }
        },
        {
          name: 'el-date-picker',
          attributes: { disabled: this.disabled, type: 'date', style: { width: '100%' } },
          formItemAttributes: { label: '失效时间', prop: 'endTime' }
        },
        {
          name: 'el-date-picker',
          attributes: {
            disabled: this.disabled,
            type: 'date',
            'value-format': 'yyyy-MM-dd HH:mm:ss',
            style: { width: '100%' }
          },
          formItemAttributes: { label: '开始购买时间', prop: 'policyStartTime' }
        },
        {
          name: 'el-radio',
          options: [
            {
              label: '是',
              value: 'YES'
            },
            {
              label: '否',
              value: 'NO'
            }
          ],
          attributes: {
            disabled: this.disabled
          },
          formItemAttributes: {
            label: '是否允许购买',
            prop: 'isBuy',
            rules: [{ required: true, message: '请选择', trigger: 'blur' }]
          }
        },

        {
          md: 6,
          name: 'el-select',
          options: [
            { value: 'AC', label: '意外险' },
            { value: 'DS', label: '第三者责任险' }
          ],
          attributes: { placeholder: '请选择', filterable: true, clearable: true },
          formItemAttributes: {
            label: '保单类型',
            prop: 'type',
            rules: [...required]
          }
        },
        {
          name: 'slot-component',
          md: 24,
          attributes: { disabled: this.disabled },
          formItemAttributes: { label: '保费率', prop: 'month1' },
          render: (h, { props }) => {
            var { formData } = props
            return (
              <div>
                <zj-table
                  columns={[
                    {
                      columnAttributes: {
                        label: '保险期间(个月)',
                        width: '110px'
                      },
                      render: (h, { row, column, index }) => {
                        return (
                          <div style="box-sizing: border-box;padding: 0 6px;">
                            {index ? '保险金额（元）' : '年费率百分比'}
                          </div>
                        )
                      }
                    },
                    ...(keys => {
                      var list = []
                      for (let i = 0; i < keys.length; i++) {
                        list.push({
                          columnAttributes: {
                            label: i + 1 + ''
                          },
                          render: (h, { row, column, index }) => {
                            if (index) {
                              return (
                                <el-form-item prop={keys[i]} label-width="0px" style="margin:0">
                                  {Math.ceil((formData[keys[i]] || 0) * (formData.policyPrice || 0)) / 100}
                                </el-form-item>
                              )
                            } else {
                              return (
                                <el-form-item
                                  prop={keys[i]}
                                  rules={this.formRules.month1}
                                  label-width="0px"
                                  style="margin:0"
                                >
                                  <el-input
                                    disabled={this.disabled}
                                    type="number"
                                    min={0}
                                    max={100}
                                    value={formData[keys[i]]}
                                    onInput={val => {
                                      formData[keys[i]] = val
                                      this.$refs?.formRef?.validateField([keys[i]], () => {})
                                    }}
                                  >
                                    <span slot="suffix">%</span>
                                  </el-input>
                                </el-form-item>
                              )
                            }
                          }
                        })
                      }
                      return list
                    })(this.monthKeys)
                  ]}
                  tableData={[{}, {}]}
                ></zj-table>
              </div>
            )
          }
        },
        {
          name: 'slot-component',
          md: 24,
          attributes: { disabled: this.disabled },
          formItemAttributes: {
            label: '保障范围',
            prop: 'policyRanges'
          },
          render: (h, { props }) => {
            var { formData } = props
            return (
              <zj-table
                columns={[
                  ...(list => {
                    return list.map(item => {
                      return {
                        columnAttributes: {
                          label: item.name,
                          prop: item.prop,
                          width: item.prop === 'options' ? '80px' : ''
                        },
                        render: (h, { row, column, index }) => {
                          return column.columnAttributes.prop === 'options' ? (
                            this.type == 1 || this.type == 0 ? (
                              <div style="box-sizing: border-box;padding: 0 6px;">
                                <el-button
                                  type="text"
                                  onClick={() => {
                                    formData.policyRanges.push({ rangeName: '', rangeText: '' })
                                  }}
                                >
                                  添加
                                </el-button>
                                {formData.policyRanges.length > 1 ? (
                                  <el-button
                                    type="text"
                                    onClick={() => {
                                      formData.policyRanges.splice(index, 1)
                                    }}
                                  >
                                    删除
                                  </el-button>
                                ) : null}
                              </div>
                            ) : null
                          ) : (
                            <el-form-item
                              label-width="0px"
                              style="margin:0"
                              prop={`policyRanges.${index}.${item.prop}`}
                              rules={[{ required: true, message: '请输入', trigger: 'blur' }]}
                            >
                              <el-input
                                disabled={this.disabled}
                                value={row[item.prop]}
                                onInput={val => {
                                  row[item.prop] = val
                                  this.$refs?.formRef?.validateField([`policyRanges.${index}.${item.prop}`], () => {})
                                }}
                              ></el-input>
                            </el-form-item>
                          )
                        }
                      }
                    })
                  })([
                    { name: '名称', prop: 'rangeName' },
                    { name: '内容', prop: 'rangeText' },
                    { name: '操作', prop: 'options' }
                  ])
                ]}
                tableData={formData.policyRanges}
              ></zj-table>
            )
          }
        },
        {
          name: 'el-input',
          attributes: { disabled: true },
          formItemAttributes: { label: '创建人', prop: 'createBy' }
        },
        {
          name: 'el-input',
          attributes: { disabled: true },
          formItemAttributes: { label: '创建时间', prop: 'createTime' }
        },
        {
          name: 'el-input',
          attributes: { disabled: true },
          formItemAttributes: { label: '修改人', prop: 'updateBy' }
        },
        {
          name: 'el-input',
          attributes: { disabled: true },
          formItemAttributes: { label: '修改时间', prop: 'updateTime' }
        }
      ]
    },
    formItems2() {
      return [
        {
          name: 'el-input',
          md: 24,
          attributes: { disabled: this.disabled },
          formItemAttributes: { label: '承保公司', prop: 'company' }
        },
        {
          name: 'slot-component',
          md: 24,
          attributes: { disabled: this.disabled },
          formItemAttributes: { label: '保单内容', prop: 'text' },
          render: (h, { props }) => {
            var { formData } = props
            return (
              <v-quill-editor
                disabled={this.disabled}
                value={formData.text}
                onInput={val => {
                  formData.text = val
                }}
              ></v-quill-editor>
            )
          }
        }
      ]
    },
    items2() {
      return [
        {
          name: 'slot-component',
          md: 24,
          attributes: {},
          formItemAttributes: { label: '', 'label-width': '0px', prop: 'policyWebsits', rules: [] },
          render: (h, { props, onInput }) => {
            var { formData } = props
            return (
              <div>
                <div>
                  <el-form
                    size="mini"
                    inline={true}
                    value={this.formInline}
                    onInput={v => {
                      this.formInline = v
                    }}
                    label-width="0px"
                  >
                    <el-form-item label="">
                      <el-input
                        value={this.formInline.websitId}
                        onInput={v => {
                          this.formInline.websitId = v
                        }}
                        placeholder="网点编号"
                      ></el-input>
                    </el-form-item>
                    <el-form-item label="">
                      <el-input
                        value={this.formInline.websitName}
                        onInput={v => {
                          this.formInline.websitName = v
                        }}
                        placeholder="网点名称"
                      ></el-input>
                    </el-form-item>
                    <el-form-item>
                      <el-button
                        type="primary"
                        onClick={() => {
                          EventBus.$emit('handlePaginationCallBack22')
                        }}
                      >
                        查询
                      </el-button>
                      <el-button
                        onClick={() => {
                          this.formInline.websitId = ''
                          this.formInline.websitName = ''
                          this.$nextTick(() => {
                            EventBus.$emit('handlePaginationCallBack22')
                          })
                        }}
                      >
                        重置
                      </el-button>
                    </el-form-item>
                  </el-form>
                </div>
                <pagingTransfer
                  handlePaginationCallBackKey="handlePaginationCallBack22"
                  value={this.formData.policyWebsits}
                  onInput={v => {
                    this.formData.policyWebsits = v
                  }}
                  left-columns={[
                    { id: 'belongCompanyCode', label: '所属公司编号', width: '160' },
                    { id: 'websitId', label: '网点编号', width: '120' },
                    { id: 'websitName', label: '网点名称', width: '' }
                  ]}
                  right-columns={[
                    { id: 'belongCompanyCode', label: '所属公司编号', width: '160' },
                    { id: 'websitId', label: '网点编号', width: '120' },
                    { id: 'websitName', label: '网点名称', width: '' }
                  ]}
                  show-pagination={false}
                  pagination-call-back={this.paginationCallback}
                  title-texts={['待选项', '已选项']}
                  min-height="300px"
                  table-row-key={row => row.websitId}
                />
              </div>
            )
          }
        }
      ]
    }
  },
  created() {
    // 获取详情
    if (this.type !== 0) {
      insureDetail({
        id: this.item.id
      }).then(res => {
        for (var key in res.data) {
          if (~this.monthKeys.indexOf(key)) {
            this.formData[key] = res.data[key] * 100
          } else if (key == 'policyRanges') {
            this.formData[key] = res?.data[key]?.length ? res.data[key] : [{ rangeName: '', rangeText: '' }]
          } else {
            this.formData[key] = res.data[key]
          }
        }
      })
    }
  },
  methods: {
    paginationCallback({ pageIndex, pageSize }) {
      return new Promise(resolve => {
        getWebsit({ ...this.formInline, attr: 'SELF' }).then(res => {
          resolve({
            total: res.data.filter(item => item.type !== 'B').length,
            data: res.data
              .filter(item => item.type !== 'B')
              .map(item => {
                return {
                  ...item,
                  websitName: item.name
                }
              })
          })
        })
      })
    },
    submit() {
      this.$refs['formRef'].validate(valid => {
        console.log(this.formData)
        if (valid) {
          ;(this.formData.id ? insureUpdate : insureAdd)({
            ...this.formData,
            startTime: dateFormat('YYYY-mm-dd HH:MM:SS', new Date(this.formData.startTime)),
            endTime: this.formData?.endTime
              ? `${dateFormat('YYYY-mm-dd HH:MM:SS', new Date(this.formData.endTime))?.split(' ')?.[0]} 23:59:59`
              : '',
            ...(() => {
              var obj = {}
              for (var key of this.monthKeys) {
                obj[key] = this.formData[key] / 100
              }
              return obj
            })()
          }).then(res => {
            this.$message({
              type: 'success',
              message: `保存成功!`
            })
            this.$emit('success')
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    reset() {
      Object.assign(this.$data, this.$options.data())
    }
  }
}
</script>

<style lang="scss" scoped></style>
