<!--
 * @Description: create
 * @Version: 1.0
 * @Autor: XuTongZhang
 * @Date: 2020-07-28 16:24:44
 * @LastEditors: XuTongZhang
 * @LastEditTime: 2020-08-11 17:27:00
-->
<template>
<div class="indexPage">
    <v-input :btn="btn" :list="list" @add="add"></v-input>
    <v-table :table="table" :tableList="tableList" :sortType="true" :queryData="queryData" @details="details" @editor="editor" @del="del"></v-table>
    <v-pager @page="callPage" :total="totalrecords"></v-pager>
    <el-dialog :visible.sync="dialogFormVisible" width="650px" :before-close="close" :close-on-click-modal="false">
        <el-form :model="form" ref="form" label-width="140px" :rules="state!==2 ? rules : {}" label-position="left">
            <el-form-item :label="$t('title.formName')" prop="formName">
                <el-input v-if="state!==2" v-model="form.formName" :placeholder="$t('message.pleaseEnter') + $t('title.formName')" autocomplete="off" maxlength="32" show-word-limit></el-input>
                <div v-else>{{form.formName}}</div>
            </el-form-item>
            <el-form-item :label="$t('title.description')" prop="formIntroduce">
                <el-input v-if="state!==2" type="textarea" :rows="4" resize="none" :placeholder="$t('message.pleaseEnter') + $t('title.description')" v-model="form.formIntroduce" maxlength="1024" show-word-limit></el-input>
                <div v-else>{{form.formIntroduce}}</div>
            </el-form-item>
            <el-form-item :label="state!==2?$t('message.selectTheRequiredFormItem'):$t('message.selectedFormItem')" prop="checkList">
                <div v-if="state!==2">{{$t('message.longFormMessage')}}</div>
                <div v-if="state!==2" style="font-size:12px;color:#999;">姓名，性别，工作年限，学历，联系电话，邮箱地址默认为已勾选项！</div>
                <el-checkbox v-if="state!==2" :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">{{$t('button.selectAll')}}</el-checkbox>
                <div v-if="state!==2" style="margin: 15px 0;"></div>
                <el-checkbox-group v-if="state!==2" v-model="form.checkList" @change="handleCheckedCitiesChange">
                    <div v-for="item in formConfigList.filter(item => item.id !== 1 && item.id !== 25 && item.type !== 2 && item.type !== 9 && item.type !== 11 && item.type !== 12)" :key="item.id">
                        <el-checkbox :label="item.id">{{item.configName + ' ' + ( [0, 11, 12, 17, 19].includes(item.type) ? $t('info.singleLineInputBox') : item.type === 1 ? $t('info.multiLineInputBox') :item.type === 8 ? $t('info.upload') : $t('info.dropDownSelectionBox'))}}</el-checkbox>
                    </div>
                </el-checkbox-group>
                <div v-else>
                    <div v-for="item in formConfigList.filter(i => form.checkList.includes(i.id))" :key="item.id">
                        <div>{{item.configName}}</div>
                        <el-input class="p10" v-if="item.type === 0" v-model="info[item.fieldName]" :placeholder="$t('message.pleaseEnter') + item.configName"></el-input>
                        <el-input class="p10" v-else-if="item.type === 1" v-model="info[item.fieldName]" type="textarea" :rows="4" resize="none" :placeholder="$t('message.pleaseEnter') + item.configName"></el-input>
                        <el-select class="p10" v-else-if="item.type === 2" v-model="info[item.fieldName]" :placeholder="$t('message.pleaseChoose') + item.configName">
                          <el-option label="男" value="男"></el-option>
                          <el-option label="女" value="女"></el-option>
                        </el-select>
                        <el-date-picker class="p10" v-else-if="item.type === 3" v-model="info[item.fieldName]" type="date" :placeholder="$t('message.pleaseChoose') + item.configName"></el-date-picker>
                        <el-cascader class="p10" v-else-if="item.type === 4" :props="{value: 'name',  label: 'name'}" v-model="info[item.fieldName]" :options="options" :placeholder="$t('message.pleaseChoose') + item.configName"></el-cascader>
                        <el-cascader class="p10" v-else-if="item.type === 5" :props="{value: 'name',  label: 'name'}" v-model="info[item.fieldName]" :options="city" :placeholder="$t('message.pleaseChoose') + item.configName"></el-cascader>
                        <!-- <el-button class="p10" v-else-if="item.type === 8" type="success" v-model="info[item.fieldName]">{{$t('message.pleaseUpload') + item.configName}}</el-button> -->
                        <el-upload
                          class="upload-demo"
                          action=""
                          v-else-if="item.type === 8"
                          :before-upload="()=>false"
                          multiple
                          :limit="3">
                          <el-button size="small" type="primary">{{$t('button.clickUpload')}}</el-button>
                        </el-upload>
                        <el-select class="p10" v-else-if="item.type === 9" v-model="info[item.fieldName]" :placeholder="$t('message.pleaseChoose') + item.configName">
                          <el-option v-for="item in educationList" :key="item.name" :label="item.name" :value="item.name"></el-option>
                        </el-select>
                        <el-cascader class="p10" v-else-if="item.type === 10" :props="{label: 'value'}" v-model="info[item.fieldName]" :options="languageList" :placeholder="$t('message.pleaseChoose') + item.configName"></el-cascader>
                        <el-input class="p10" v-if="item.type === 11" v-model="info[item.fieldName]" :placeholder="$t('message.pleaseEnter') + item.configName"></el-input>
                        <el-input class="p10" v-if="item.type === 12" v-model="info[item.fieldName]" :placeholder="$t('message.pleaseEnter') + item.configName"></el-input>
                        <el-date-picker class="p10" v-else-if="item.type === 13" v-model="info[item.fieldName]" type="date" :placeholder="$t('message.pleaseChoose') + item.configName"></el-date-picker>
                        <el-date-picker class="p10" v-else-if="item.type === 14" v-model="info[item.fieldName]" type="date" :placeholder="$t('message.pleaseChoose') + item.configName"></el-date-picker>
                        <el-date-picker class="p10" v-else-if="item.type === 15" v-model="info[item.fieldName]" type="date" :placeholder="$t('message.pleaseChoose') + item.configName"></el-date-picker>
                        <el-date-picker class="p10" v-else-if="item.type === 16" v-model="info[item.fieldName]" type="date" :placeholder="$t('message.pleaseChoose') + item.configName"></el-date-picker>
                        <el-input class="p10" v-else-if="item.type === 17" v-model="info[item.fieldName]" :placeholder="$t('message.pleaseEnter') + item.configName"></el-input>
                        <el-select class="p10" v-else-if="item.type === 18" v-model="info[item.fieldName]" :placeholder="$t('message.pleaseChoose') + item.configName">
                          <el-option v-for="item in experienceList" :key="item.name" :label="item.name" :value="item.name"></el-option>
                        </el-select>
                        <el-input type="number" class="p10" v-else-if="item.type === 19" v-model="info[item.fieldName]" :placeholder="$t('message.pleaseEnter') + item.configName"></el-input>
                    </div>
                </div>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="close">{{$t('button.cancel')}}</el-button>
            <el-button type="primary" v-if="state!==2" @click="determine">{{$t('button.generateForm')}}</el-button>
        </div>
    </el-dialog>
</div>
</template>

<script>
import addr from '../../common/addr'
export default {
  data () {
    let validcodeName = (rule, value, callback) => {
      if (!value.length) {
        callback(new Error(this.$t('message.selectTheRequiredFormItem')))
      } else {
        callback()
      }
    }
    return {
      tableList: [],
      educationList: [{ name: this.$t('info.juniorCollege') }, { name: this.$t('info.undergraduate') }, { name: this.$t('info.masterSDegree') }, { name: this.$t('info.phD') }, { name: this.$t('info.other') }],
      experienceList: [{ name: '1年以内工作经验' }, { name: '1-3年工作经验' }, { name: '3-5年工作经验' }, { name: '5-10年工作经验' }, { name: '10年以上工作经验' }],
      dialogFormVisible: false,
      page: 1,
      state: 0,
      checkAll: false,
      isIndeterminate: true,
      form: {
        formName: '',
        formIntroduce: '',
        checkList: []
      },
      formConfigList: [],
      totalrecords: 0,
      pickList: [],
      rules: {
        formName: [{
          required: true,
          message: this.$t('message.pleaseEnter') + this.$t('title.formName'),
          trigger: 'blur'
        }],
        formIntroduce: [{
          required: true,
          message: this.$t('message.pleaseEnter') + this.$t('title.description'),
          trigger: 'blur'
        }],
        checkList: [{
          validator: validcodeName,
          trigger: 'blur'
        }]
      },
      options: addr.addr,
      info: {},
      list: [],
      btn: [{
        name: this.$t('button.addTo'),
        type: 'success',
        method: 'add'
      }],
      table: {
        column: [{
          label: this.$t('field.serialNumber'),
          props: 'serialNumber'
        },
        {
          label: this.$t('field.formName'),
          props: 'formName'
        },
        {
          label: this.$t('field.description'),
          props: 'formIntroduce'
        }
        ],
        handle: [{
          title: this.$t('button.view'),
          method: 'details',
          type: 'info'
        },
        {
          title: this.$t('button.edit'),
          method: 'editor',
          type: 'warning'
        },
        {
          title: this.$t('button.delete'),
          method: 'del',
          type: 'danger'
        }
        ]
      }
    }
  },
  computed: {
    city () {
      let options = JSON.parse(JSON.stringify(this.options))
      return options.map(item => {
        item.children = item.children.map(item => {
          delete item.children
          return item
        })
        return item
      })
    },
    languageList () {
      let list = ['不限', '英语', '日语', '俄语', '阿拉伯语', '法语', '德语', '西班牙语', '葡萄牙语', '意大利语', '韩语/朝鲜语', '普通话', '粤语', '闽南话', '上海话', '其他']
      let children = ['一般', '良好', '熟练', '精通']
      children = children.map(item => ({ value: item }))
      return list.map(item => ({ children, value: item }))
    }
  },
  created () {
    console.log(this.options)
    this.queryData()
    this.queryFormConfigList()
    console.log(this.languageList)
  },
  methods: {
    queryData (form = {}) {
      let page = this.page
      let reqdata = form
      this.$api
        .post('/form/queryFormList', {
          reqdata,
          page
        })
        .then((res) => {
          this.totalrecords = res.totalrecords
          this.tableList = res.list.map((item, index) => {
            item.serialNumber = (this.page - 1) * 10 + index + 1
            return item
          })
        })
    },
    queryFormConfigList () {
      this.$api
        .post('/formConfig/queryFormConfigList', {
          reqdata: {},
          rows: 50
        })
        .then((res) => {
          this.formConfigList = res.list
        })
    },
    add () {
      this.open()
      this.info = {}
      this.state = 0
    },
    getDetails (row) {
      let reqdata = {
        id: row.id
      }
      this.$api
        .post('/form/queryFormDetail', {
          reqdata
        })
        .then((res) => {
          this.open()
          this.form = res.object
          this.$set(this.form, 'checkList', JSON.parse(res.object.formConfig).map(item => item.id))
        })
    },
    details (row) {
      this.getDetails(row)
      this.state = 2
    },
    editor (row) {
      this.getDetails(row)
      this.state = 1
    },
    del (row) {
      this.$confirm(this.$t('message.confirmMessage') + '?', this.$t('info.prompt'), {
        confirmButtonText: this.$t('info.determine'),
        cancelButtonText: this.$t('info.cancel'),
        type: 'warning'
      }).then(() => {
        let reqdata = {
          id: row.id
        }
        this.$api
          .post('/form/deleteForm', {
            reqdata
          })
          .then((res) => {
            this.$message({
              message: this.$t('message.successfullyModified') + '!',
              type: 'success'
            })
            this.queryData()
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$t('message.undeleted') + '!'
        })
      })
    },
    determine () {
      console.log(this.form)
      let a
      this.$refs['form'].validate((valid) => {
        a = valid
      })
      if (!a) return
      let array = []
      this.formConfigList.forEach(item => {
        (item.id === 1 || item.id === 25 || item.type === 2 || item.type === 9 || item.type === 11 || item.type === 12) &&
        array.push(item)
      })
      this.form.checkList.forEach(item => {
        array.push(this.formConfigList.find(i => i.id === item))
      })
      console.log(this.form)
      let url = this.state ? '/form/updateForm' : '/form/saveForm'
      let reqdata = this.form
      reqdata.formConfig = JSON.stringify(Array.from(new Set(array)))
      this.$api
        .post(url, {
          reqdata
        })
        .then((res) => {
          this.close()
          this.queryData()
        })
    },
    open () {
      this.dialogFormVisible = true
    },
    close () {
      this.dialogFormVisible = false
      this.form = {
        formName: '',
        formIntroduce: '',
        checkList: []
      }
      this.info = {}
    },
    callPage (val) {
      this.page = val
      this.queryData()
    },
    handleCheckAllChange (val) {
      this.$set(this.form, 'checkList', val ? this.formConfigList.map(item => item.id) : [])
      this.isIndeterminate = false
    },
    handleCheckedCitiesChange (value) {
      let checkedCount = value.length
      this.$set(this.$data, 'checkAll', checkedCount === this.formConfigList.length)
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.formConfigList.length
    }
  },
  watch: {
    dialogFormVisible: function (val, oldVla) {
      if (this.state === 2) {
        if (this.$refs['form'] !== undefined) {
          this.$refs['form'].resetFields()
        }
      }
    },
    'form.checkList' (val) {
      this.$set(this.$data, 'checkAll', val.length === this.formConfigList.length)
      this.isIndeterminate = !!val.length && val.length !== this.formConfigList.length
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog-footer {
    display: flex;
    justify-content: center;
    align-items: center;
}

.p10 {
    padding: 8px 0 8px 0;
}
</style>
