<script lang="ts">
import Vue from 'vue'
import { saveForm, getFormInfo } from '@/api/form'
import guide from '@/views/components/guidePopover.vue'
import draggable from 'vuedraggable'
import countryCode from '@/lib/countryCode.json'

export default Vue.extend({
  name: 'Edit',
  components: {
    draggable,
    guide
  },
  data() {
    return {
      compList: [
        {
          type: 'input',
          name: 'first_name',
          label: '请在下方输入名字',
          value: '',
          width: 3,
          placeholder: '请输入名字',
          required: false
        },
        {
          type: 'input',
          name: 'last_name',
          label: '请在下方输入姓氏',
          value: '',
          width: 3,
          placeholder: '请输入姓氏',
          required: false
        },
        {
          type: 'select',
          name: 'id_type',
          label: '请在下方选择证件类型',
          value: '',
          width: 2,
          options: [
            { label: '身份证', value: 'id' },
            { label: '护照', value: 'passport' }
          ],
          placeholder: '请选择',
          required: false
        },
        {
          type: 'input',
          name: 'id_number',
          label: '请在下方输入证件号码',
          value: '',
          width: 4,
          placeholder: '请输入证件号码',
          required: false
        },
        {
          type: 'phone',
          name: 'mobile_country_code',
          label: '请在下方输入手机国家代码',
          value: '',
          country: 'CN',
          width: 2,
          placeholder: '请输入手机号',
          required: false
        },
        {
          type: 'input',
          name: 'mobile',
          label: '请在下方输入手机号码',
          value: '',
          country: 'CN',
          width: 4,
          placeholder: '请输入手机号',
          required: false
        },
        {
          type: 'input',
          name: 'email',
          label: '请在下方输入邮箱',
          value: '',
          width: 6,
          placeholder: '请输入邮箱',
          codePlaceholder: '请输入验证码',
          required: false
        },
        {
          type: 'input',
          name: 'company',
          label: '请在下方输入公司名称',
          value: '',
          width: 2,
          placeholder: '请输入公司名称',
          required: false
        },
        {
          type: 'input',
          name: 'department',
          label: '请在下方输入部门名称',
          value: '',
          width: 2,
          placeholder: '请输入部门名称',
          required: false
        },
        {
          type: 'select',
          name: 'position',
          label: '请在下方选择职位',
          value: '',
          width: 2,
          options: [
            { label: '职位', value: '职位' }
          ],
          placeholder: '请选择',
          required: false
        },
        {
          type: 'select',
          name: 'country',
          label: '请在下方选择国家',
          value: '',
          width: 2,
          options: [
            { label: '国家', value: '国家' }
          ],
          placeholder: '请选择',
          required: false
        },
        {
          type: 'select',
          name: 'province',
          label: '请在下方选择省份',
          value: '',
          width: 2,
          options: [
            { label: '省份', value: '省份' }
          ],
          placeholder: '请选择',
          required: false
        },
        {
          type: 'select',
          name: 'city',
          label: '请在下方选择市',
          value: '',
          width: 2,
          options: [
            { label: '市', value: '市' }
          ],
          placeholder: '请选择',
          required: false
        },
        {
          type: 'input',
          name: 'address',
          label: '请在下方输入地址',
          value: '',
          width: 6,
          placeholder: '请输入地址',
          required: false
        },
        {
          type: 'select',
          name: 'industry',
          label: '请在下方选择行业',
          value: '',
          width: 2,
          options: [
            { label: '行业', value: '行业' }
          ],
          placeholder: '请选择',
          required: false
        },
        {
          type: 'input',
          name: 'interested_products',
          label: '感兴趣的产品',
          value: '',
          width: 3,
          placeholder: '请输入地址',
          required: false
        },
        {
          type: 'input',
          name: 'business_type',
          label: '业务性质',
          value: '',
          width: 3,
          placeholder: '请输入地址',
          required: false
        },
      ],
      formData: [],
      trashData: [],
      formInfo: {
        name: '未命名表单',
        desc: '从右侧拖动组件到表单区域',
        id: ''
      },
      isDrag: false,
      currentKey: '',
      currentData: {},
      hoverKey: '',
      selectInput: '',
      countryCode,
      loading: false
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      function getType(name) {
        if (['first_name', 'last_name', 'email' ,'id_number', 'company', 'department', 'address','country','interested_products','business_type','mobile'].includes(name)) {
          return 'input'
        }
        if (['id_type', 'position', 'province', 'city', 'industry'].includes(name)) {
          return 'select'
        }
        if (['mobile_country_code'].includes(name)) {
          return 'phone'
        }
      }
      if (this.$route.params.id) {
        this.loading = true
        this.formInfo.id = this.$route.params.id
        getFormInfo(this.formInfo.id).then(res => {
          this.loading = false
          this.formInfo.name = res.data.template_name
          this.formInfo.desc = res.data.description
          res.data.fields.forEach(fields => {
            this.compList.forEach(item => {
              if (fields.field_name === item.name) {
                this.formData.push({
                  key: fields.id,
                  type: getType(fields.field_name),
                  name: fields.field_name,
                  label: fields.field_label,
                  value: '',
                  width: item.width,
                  placeholder: '请输入',
                  required: fields.is_required ? 1 : 0
                })
              }
            })
          })
          console.log(res)
        }).catch(err => {
          this.loading = false
        })
      }
    },
    save() {
      if (this.loading) {
        return
      }
      this.loading = true
      const saveData = []
      this.formData.forEach(item => {
        saveData.push({
          field_name: item.name,
          field_label: item.label,
          is_required: item.required? 1 : 0
        })
      })
      saveForm(this.formInfo.id, this.formInfo.name, this.formInfo.desc, saveData).then(res => {
        this.loading = false
        this.$message.success('保存成功')
        this.$router.push('/preRegister/list')
        console.log(res)
      }).catch(err => {
        this.loading = false
        this.$message.error('保存失败')
        console.log(err)
      })
    },
    choseComp(element) {
      this.currentKey = element.key
      this.currentData = element
    },
    removeComp(element) {
      this.$confirm('确定删除吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        callback: action => {
          if (action === 'confirm') {
            const index = this.getIndexByKey(element.key)
            this.formData.splice(index, 1)
            this.currentKey = ''
          }
        }
      })
    },
    addSelectItem() {
      if (this.selectInput.length === 0) { return }
      this.currentData.options.push({
        label: this.selectInput,
        value: this.selectInput
      })
      this.selectInput = ''
    },
    removeSelectItem(index) {
      this.currentData.options.splice(index, 1)
    },
    cloneItem(item) {
      const newItem = JSON.parse(JSON.stringify(item))
      newItem.key = newItem.type + new Date().getTime()
      return newItem
    },
    removeTrash(element) {
      const index = this.getIndexByKey(element.key)
      this.trashData.splice(index, 1)
    },
    hover(element) {
      if (this.isDrag) return
      this.hoverKey = element.key
    },
    blur(element) {
      this.hoverKey = ''
    },
    getIndexByKey(key) {
      return this.formData.indexOf(this.formData.find(item => item.key === key))
    },
    handleStart() {
      this.isDrag = true
      this.formData.forEach(item => {
        item.hover = false
      })
    },
    handleEnd() {
      this.isDrag = false
    }
  }
})
</script>

<template>
  <div v-loading="loading" class="main-box">
    <div class="comp-lib">
      <div class="title">
        组件库
      </div>
      <div class="list">
        <draggable v-model="compList" :options="{sort:false}" :group="{name:'form',put:false,pull:'clone'}" :clone="cloneItem" class="drag-list">
          <transition-group class="drag-cont">
            <div v-for="(element) in compList" :key="element.name">
              <div v-if="element.type==='input'" :class="[element.type,'form-item']">
                <div class="tips">{{ element.label }}</div>
                <el-input :value="element.value" :placeholder="element.placeholder" />
              </div>
              <div v-if="element.type==='phone'" :class="[element.type,'form-item']">
                <div class="tips">{{ element.label }}</div>
                <div class="phone-input">
                  <el-select v-model="element.country" :placeholder="element.placeholder">
                    <el-option v-for="(item,index) in countryCode" :key="item.country_code+index" :label="'+'+item.phone_code+'('+item.chinese_name+')'" :value="item.country_code" />
                  </el-select>
                </div>
              </div>
              <div v-if="element.type==='select'" :class="[element.type,'form-item']">
                <div class="tips">{{ element.label }}</div>
                <el-select :value="element.value" :placeholder="element.placeholder">
                  <el-option v-for="item in element.options" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </div>
            </div>
          </transition-group>
        </draggable>
      </div>
    </div>
    <div class="form-view">
      <div class="scroll-view">
        <div class="form-cont">
          <div :class="['form-head',getIndexByKey(currentKey) === -1?'active':'']" @click="currentKey=''">
            <div class="title">{{ formInfo.name }}</div>
            <div class="tips">{{ formInfo.desc }}</div>
          </div>
          <draggable v-model="formData" :group="{name:'form'}" :options="{sort:true,animation:300}" class="form-body" @start="handleStart" @end="handleEnd">
            <transition-group class="drag-cont">
              <div v-for="element in formData" :key="element.key" :style="{gridColumn:'span '+element.width}" :class="[element.required?'required':'']" @click="choseComp(element)" @mouseenter="hover(element)" @mouseleave="blur(element)">
                <div v-if="element.type==='input'" :class="[element.type,'form-item','view',{'active':element.key===hoverKey||element.key===currentKey}]">
                  <div class="tips">{{ element.label }}</div>
                  <el-input :value="element.value" :placeholder="element.placeholder" />
                </div>
                <div v-if="element.type==='email'" :class="[element.type,'form-item','view',{'active':element.key===hoverKey||element.key===currentKey}]">
                  <div class="tips">{{ element.label }}</div>
                  <div>
                    <el-input v-model="element.value" :placeholder="element.placeholder" />
                  </div>
                  <div class="code-input">
                    <el-input v-model="element.value" :placeholder="element.codePlaceholder" />
                    <el-button>获取验证码</el-button>
                  </div>
                </div>
                <div v-if="element.type==='phone'" :class="[element.type,'form-item','view',{'active':element.key===hoverKey||element.key===currentKey}]">
                  <div class="tips">{{ element.label }}</div>
                  <div class="phone-input">
                    <el-select v-model="element.country" :placeholder="element.placeholder">
                      <el-option v-for="(item,index) in countryCode" :key="item.country_code+index" :label="'+'+item.phone_code+'('+item.chinese_name+')'" :value="item.country_code" />
                    </el-select>
                  </div>
                </div>
                <div v-if="element.type==='select'" :class="[element.type,'form-item','view',{'active':element.key===hoverKey||element.key===currentKey}]">
                  <div class="tips">{{ element.label }}</div>
                  <el-select :value="element.value" :placeholder="element.placeholder">
                    <el-option v-for="item in element.options" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </div>
              </div>
            </transition-group>
          </draggable>
        </div>
      </div>
    </div>
    <div class="comp-edit">
      <template v-if="getIndexByKey(currentKey) === -1">
        <div class="button">
          <el-button type="primary" @click="save">保存表单</el-button>
        </div>
        <div class="title">表单设定</div>
        <div class="body">
          <div class="tips">表单名称</div>
          <el-input v-model="formInfo.name" placeholder="请输入表单名称" />
          <div class="tips">表单介绍</div>
          <el-input v-model="formInfo.desc" type="textarea" placeholder="请输入表单介绍" />
        </div>
      </template>
      <template v-else>
        <div />
        <div class="title">
          <span class="el-icon-arrow-left icon" @click="currentKey=''" />
          组件设定
        </div>
        <div class="body">

          <div class="tips">
            表单项介绍
            <guide
              video="/static/guide/表单项介绍.jpg"
              title="表单项介绍"
              text="展示在输入框上方的大段文本，用于介绍和提示该处应输入的内容。"
            />
          </div>
          <el-input v-model="currentData.label" type="textarea" placeholder="请输入表单项介绍" />

          <template>
            <div class="tips">是否必填</div>
            <el-switch v-model="currentData.required" />
          </template>

        </div>
        <div class="button">
          <el-button type="danger" @click="removeComp(currentData)">删除组件</el-button>
        </div>
      </template>
    </div>
    <div :class="['trash-bin',isDrag?'':'hide']">
      <div class="trash-inner">
        <draggable v-model="trashData" :group="{name:'form'}" :options="{sort:false,animation:300}" :class="['trash-cont',trashData.length?'':'hide']">
          <transition-group class="drag-cont">
            <div v-for="element in trashData" :key="element.key" class="form-item view">
              <div class="tips">{{ element.label }}</div>
              <div class="del el-icon-delete" @click="removeTrash(element)" />
            </div>
          </transition-group>
        </draggable>
      </div>
      <div class="text">回收站</div>
    </div>
  </div>
</template>

<style scoped>
  .main-box{
    position: relative;
    overflow: hidden;
    padding: 0 !important;
    height: 100%;
    width: 100%;
    display: grid;
    grid-template-columns: 360px 1fr 360px;
    grid-template-rows: 1fr;
    .form-item{
      cursor: grab;
      background: white;
      margin-bottom: -1px;
      border-top: 1px solid lightgrey;
      border-bottom: 1px solid lightgrey;
      padding: 24px;
      .tips{
        font-size: 15px;
        color: #989898;
        margin-bottom: 8px;
      }
      &.email{
        .code-input{
          display: flex;
          grid-gap: 8px;
          margin-top: 8px;
        }
      }
      &.phone{
        .el-select{
          display: flex;
          grid-gap: 8px;
        }
      }
      &.select{
        .el-select{
          width: 100%;
        }
      }
      &.number{
        .el-input-number{
          width: 100%;
        }
      }
      &.time,&.timeRange{
        .el-date-editor{
          width: 100%;
        }
      }
      &.date,&.dateRange{
        .el-date-editor{
          width: 100%;
        }
      }
      &.region{
        .el-cascader{
          width: 100%;
        }
      }
      &.view{
        transition-duration: 300ms;
        border-radius: 8px;
        border: 3px solid #2563EB00;
        padding: 12px 12px;
        margin-bottom: 0;
        &.tips{
          padding: 12px 12px;
        }
        &.active{
          border: 3px solid #2563EB;
        }
      }
    }
    .trash-bin{
      box-shadow: -4px 8px 12px 0 #00000044;
      padding: 8px;
      position: absolute;
      border-radius: 32px 32px 0 0;
      z-index: 3;
      right: 200px;
      bottom: 0;
      width: 360px;
      height: 150px;
      background: lightgrey;
      transition-duration: 300ms;
      .trash-inner{
        position: relative;
        outline: #e4e4e4 5px solid;
        border-radius: 24px;
        width: 100%;
        height: 60px;
        background-image: linear-gradient( #b3b3b3, #2b2b2b);
        .trash-cont{
          overflow: hidden;
          border-radius: 24px;
          position: absolute;
          width: 100%;
          height: 200%;
          left: 0;
          bottom: 0;
          &.hide{
            height: 100%;
          }
          .drag-cont{
            padding: 6px 12px 0;
            overflow: hidden;
            overflow-y: scroll;
            display: block;
            width: calc(100% + 20px);
            height: 100%;
            .form-item{
              position: sticky;
              left: 0;
              top: 0;
              border-bottom-right-radius: 0;
              border-bottom-left-radius: 0;
               border: 1px solid lightgrey;
              height: 100%;
              .del{
                position: absolute;
                right: 16px;
                top: 16px;
                cursor: pointer;
              }
            }
          }
        }
      }
      .text{
        width: 100%;
        text-align: center;
        margin-top: 16px;
        font-size: 36px;
        font-weight: bold;
        color: gray;
        text-shadow: 4px 4px 4px 4px #ffffff;
      }
      &.hide{
        bottom: -160px;
      }
      &:hover{
        bottom: -60px;
      }
    }
    .comp-lib{
      z-index: 1;
      position: relative;
      display: grid;
      grid-template-rows: auto 1fr;
      box-shadow: 0 1px 4px 0 #00000022;
      .title{
        padding: 24px;
      }
      .list{
        position: relative;
        .drag-list{
          position: absolute;
          top: 0;
          left: 0;
          height: 100%;
          width: 100%;
          overflow: hidden;
          overflow-y: auto;
          .drag-cont{
            width: 100%;
            height: 100%;
            display: block;
          }
        }
      }
    }
    .form-view{
      position: relative;
      background: #F9FAFB;
      .scroll-view{
        position: absolute;
        left: 0;
        top: 0;
        height: 100%;
        width: 100%;
        overflow: hidden;
        overflow-y: scroll;
        .form-cont{
          padding: 12px;
          border-radius: 16px;
          margin: 24px;
          background: white;
          width: calc(100% - 48px);
          box-shadow: 0 1px 4px 0 #00000022;
          .form-head{
            padding: 12px;
            border-radius: 8px;
            transition-duration: 300ms;
            border: 3px solid #2563EB00;
            &:hover,&.active{
              border: 3px solid #2563EB;
            }
            .title{
              font-size: 36px;
              font-weight: bold;
            }
            .tips{
              font-size: 20px;
              color: #989898;
              margin-bottom: 6px;
            }
          }
          .form-body{
            .drag-cont{
              display: grid;
              grid-template-columns: 1fr 1fr 1fr 1fr 1fr 1fr;
              width: 100%;
              min-height: 300px;
              align-content: start;
              .form-item{
                height: fit-content;
              }
              .required{
                .tips{
                  &::after{
                    margin-left: 4px;
                    content: '*';
                    color: red;
                  }
                }
              }
            }
          }
        }
      }
    }
    .comp-edit{
      z-index: 1;
      position: relative;
      box-shadow: 0 1px 4px 0 #00000022;
      display: grid;
      grid-template-rows: auto auto 1fr auto;
      .body{
        padding: 0 16px;
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        .tips{
          width: 100%;
          font-size: 16px;
          color: #505050;
          margin-bottom: 6px;
          margin-top: 12px;
        }
        .pattern-select{
          margin-top: 6px;
          width: 100%;
        }
        .select-list{
          width: 100%;
          .handel{
            height: 100%;
            display: flex;
            align-items: center;
          }
          .select-inner{
            .el-input__inner{
              cursor: grab;
            }
          }
        }
      }
      .button{
        display: flex;
        justify-content: flex-end;
        padding: 16px;
      }
      .title{
        padding: 16px;
        display: flex;
        align-items: center;
        .icon{
          margin-left: -4px;
          margin-top: -4px;
          margin-right: 8px;
          font-size: 24px;
          cursor: pointer;
          padding: 4px;
          border-radius: 8px;
          transition-duration: 300ms;
          &:hover{
            color: #2563EB;
            background: #ececec;
          }
        }
      }
    }
  }
</style>
