<template>
  <task-design-view :processIndex="2" :taskTemplateName="templateName" @saveData="handleTitleChange" @preview="preview">
    <div class="task-design-content">
      <!--    <div>-->
      <!--      &lt;!&ndash;        <el-button type="primary" @click="saveForm">保存</el-button>&ndash;&gt;-->
      <!--      <a-button style="position: fixed;right: 20px;top: 18px;z-index: 101;" @click="saveForm">保存</a-button>-->

      <!--<div style="text-align: right">-->
      <!--<el-button style="margin-right: 20px" type="primary" @click="saveForm">保存</el-button>-->
      <!--</div>-->
      <el-row style="background-color: rgb(240,242,245);padding-top: 10px;display: flex">
        <el-col :span="6" class="col createForm" style="">
          <div class="tab">
            <span>控件库</span>
          </div>
          <el-form ref="form" class="b-a" label-width="110px" style="padding: 0 20px">
            <draggable
              :clone="cloneData"
              @start="startFun"
              @end="endFun"
              :list="form_list"
              :options="dragOptions1"
              @setData="changeValue">
              <transition-group class="form-list-group" type="transition" :name="'flip-list'" tag="div">
                <template v-for="(item,index) in form_list">
                  <div :key="index" class="card">
                    <label>{{ item.obj.name }}</label>
                    <img class="widgeticon" :src="iconConfig[item.obj.fieldTp]" alt="">
                  </div>
                </template>
              </transition-group>
            </draggable>
          </el-form>
        </el-col>
        <el-col :span="10" style="display: flex;justify-content: center">
          <div class="cfc_main">
            <div class="createFormCenter">
              <el-form disabled ref="form" class="b-a" label-width="120px" label-position="left">
                <draggable style="height: 480px;" :clone="cloneData" :list="list2" :options="dragOptions2">
                  <transition-group
                    class=""
                    style="height: 100%;padding-top: 10px"
                    type="transition"
                    :name="'flip-list'"
                    tag="div">
                    <renders
                      :class="{'activeItem':currentItemIndex === index}"
                      v-for="(items, index) in list2"
                      :key="index"
                      :ele="items.obj.fieldTp"
                      :obj="items.obj"
                      :index="index"
                      @changeinnerList="changeInnerList"
                      @ShowFormInner="selectFormInner"
                      @ShowForm="selectForm"
                      @handleRemoveEle="removeEle"
                      @handleChangeVal="val => handleChangeVal(val,element)"></renders>
                  </transition-group>
                </draggable>
              </el-form>
            </div>
          </div>
        </el-col>
        <el-col v-show="isFormShow" :span="8" class="col1 createForm">
          <span class="formTitle">{{ this.modalFormData.name }}</span>
          <hr style="height: 2px;opacity: 0.2;background-color: #00000030;">
          <el-form
            ref="modalFormData"
            :model="modalFormData"
            label-position="top"
            style="margin-left: 40px"
            label-width="120px">
            <!--通用-->
            <el-form-item label="标题" v-if="typeof modalFormData.fieldNm != 'undefined'">
              <el-input v-model="modalFormData.fieldNm" @blur="onSubmit"></el-input>
            </el-form-item>

            <el-form-item label="说明文字" v-if="typeof modalFormData.explainText != 'undefined'">
              <el-input v-model="modalFormData.explainText" @blur="onSubmit"></el-input>
            </el-form-item>

            <el-form-item label="跳转链接" v-if="typeof modalFormData.linkUrl != 'undefined'">
              <el-input v-model="modalFormData.linkUrl" @blur="onSubmit"></el-input>
              <span>必须带着前缀(http://  https://)</span>
            </el-form-item>
            <el-form-item label="提示文字" v-if="typeof modalFormData.fieldHint != 'undefined'">
              <el-input v-model="modalFormData.fieldHint" @blur="onSubmit"></el-input>
            </el-form-item>

            <el-form-item label="开始提示文字" v-if="typeof modalFormData.startPlaceholder != 'undefined'">
              <el-input
                v-model="modalFormData.startPlaceholder"
                :placeholder="modalFormData.startPlaceholder"
                @blur="onSubmit"></el-input>
            </el-form-item>

            <el-form-item label="结束提示文字" v-if="typeof modalFormData.endPlaceholder != 'undefined'">
              <el-input
                v-model="modalFormData.endPlaceholder"
                :placeholder="modalFormData.endPlaceholder"
                @blur="onSubmit"></el-input>
            </el-form-item>

            <el-form-item label="动作名称" v-if="typeof modalFormData.btnText != 'undefined'">
              <el-input v-model="modalFormData.btnText" @blur="onSubmit"></el-input>
            </el-form-item>

            <el-form-item label="单位" v-if="typeof modalFormData.unit != 'undefined'">
              <el-select v-model="modalFormData.unit" placeholder="请选择单位">
                <el-option label="区域一" value="shanghai"></el-option>
                <el-option label="区域二" value="beijing"></el-option>
              </el-select>
            </el-form-item>

            <!--<el-form-item label="关联设备范围 (读取设备管理数据库)" v-if="typeof modalFormData.equipmentRange != 'undefined'">
              <el-select v-model="modalFormData.equipmentRange" @change="onSubmit" placeholder="请选择">
                <el-option :label="item.name" :value="item.code" v-for="(item,index) in equipmentRangeList"></el-option>
              </el-select>
              <br/>
              <span>不选择,则默认关联全部设备管理数据</span>
            </el-form-item>-->

            <!-- <el-form-item label="显示" v-if="typeof modalFormData.showDetailType != 'undefined'">
              <el-checkbox-group style="display: flex;flex-direction: column" @change="onSubmit" v-model="modalFormData.showDetailType">
                <el-checkbox true-label="1"  label="显示全部人员名单"></el-checkbox>
                <el-checkbox true-label="2" label="仅显示已读人员名单"></el-checkbox>
                <el-checkbox true-label="3" label="仅显示未读人员名单"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>-->

            <el-form-item label="选项" v-if="typeof modalFormData.isMultiple != 'undefined'">
              <el-radio-group v-model="modalFormData.isMultiple" @change="onSubmit">
                <el-radio style="margin-bottom: 10px" :label="false">只能选择一个部门</el-radio>
                <el-radio :label="true">可同时选择多部门</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="日期类型" v-if="typeof modalFormData.dateType != 'undefined'">
              <el-radio-group v-model="modalFormData.dateType" @change="onSubmit">
                <el-radio style="margin-bottom: 10px" :label="'datetime'">年-月-日 时：分</el-radio>
                <el-radio :label="'date'">年-月-日</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="日期类型" v-if="typeof modalFormData.dateRangeType != 'undefined'">
              <el-radio-group v-model="modalFormData.dateRangeType" @change="onSubmit">
                <el-radio style="margin-bottom: 10px" :label="'datetime'">年-月-日 时：分</el-radio>
                <el-radio :label="'date'">年-月-日</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="选项" v-if="typeof modalFormData.items != 'undefined'">
              <div v-for="(item,index) in modalFormData.items" class="disFlex">
                <el-input v-model="item.label" :placeholder="item.label"></el-input>
                <i class="el-icon-plus" @click="addItems(index)" style="margin: 0 20px"></i>
                <i class="el-icon-delete" @click="delItems(index)"></i>
              </div>
            </el-form-item>

            <!--<el-form-item label="输入长度限制">-->
            <!--<el-input v-model="modalFormData.maxLength"></el-input>-->
            <!--</el-form-item>-->
            <el-form-item label="验证" v-if="typeof modalFormData.required != 'undefined'">
              <el-checkbox
                v-model="modalFormData.required"
                true-label="1"
                false-label="0"
                @change="onSubmit">
              </el-checkbox>
              <span>必填</span>
            </el-form-item>

            <!--<el-form-item label="自动计算时长" v-if="typeof modalFormData.autoCount != 'undefined'">
              <el-checkbox
                v-model="modalFormData.autoCount"
                true-label="1"
                false-label="0">
              </el-checkbox>
              <span>启用</span>
            </el-form-item>-->

            <!--<el-form-item label="打印" v-if="typeof modalFormData.print != 'undefined'">
              <el-checkbox
                v-model="modalFormData.print"
                true-label="1"
                false-label="0">
              </el-checkbox>
              <span>参与打印（不勾选，则打印时不显示该项）</span>
            </el-form-item>-->

            <!-- <el-form-item label="水印照片" v-if="typeof modalFormData.isWatermark != 'undefined'">
              <el-checkbox
                v-model="modalFormData.isWatermark"
                true-label="1"
                false-label="0">
              </el-checkbox>
              <span>开启后图片上传只能通过手机拍照方式，附加水印</span>
            </el-form-item>-->

            <!--<el-form-item label="显示" v-if="typeof modalFormData.major != 'undefined'">
              &lt;!&ndash;<el-switch&ndash;&gt;
              &lt;!&ndash;v-model="modalFormData.major"&ndash;&gt;
              &lt;!&ndash;active-color="#13ce66"&ndash;&gt;
              &lt;!&ndash;:active-value="'1'"&ndash;&gt;
              &lt;!&ndash;:inactive-value="'0'"&ndash;&gt;
              &lt;!&ndash;inactive-color="#ff4949">&ndash;&gt;
              &lt;!&ndash;</el-switch>&ndash;&gt;
              <el-checkbox
                v-model="modalFormData.major"
                true-label="1"
                false-label="0">
              </el-checkbox>
              <span>关键信息（勾选后，则作为关键信息显示在列表面板中）</span>
            </el-form-item>-->

            <!--   <el-form-item label="条件" v-if="typeof modalFormData.condition != 'undefined'">
              <el-checkbox
                v-model="modalFormData.condition"
                true-label="1"
                false-label="0">
              </el-checkbox>
              &lt;!&ndash;<el-switch&ndash;&gt;
              &lt;!&ndash;v-model="modalFormData.condition"&ndash;&gt;
              &lt;!&ndash;active-color="#13ce66"&ndash;&gt;
              &lt;!&ndash;:active-value="'1'"&ndash;&gt;
              &lt;!&ndash;:inactive-value="'0'"&ndash;&gt;
              &lt;!&ndash;inactive-color="#ff4949">&ndash;&gt;
              &lt;!&ndash;</el-switch>&ndash;&gt;
              <span>可作为条件参与流程设置</span>
            </el-form-item>-->

            <!--<el-form-item>-->
            <!--<el-button type="primary" @click="onSubmit">立即创建</el-button>-->
            <!--</el-form-item>-->
          </el-form>
        </el-col>
      </el-row>
    </div>
    <div class="previewDialog">
      <el-dialog title="预览表单" :visible.sync="isShowPreviewDialog">
        <el-form :model="previewForm">
          <renders
            v-for="(items, index) in list2"
            :key="index"
            :ele="items.obj.fieldTp"
            :obj="items.obj"
            :index="index"
            @handleChangeVal="val => handleChangeVal(val,element)"></renders>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="isShowPreviewDialog = false">取 消</el-button>
          <el-button type="primary" @click="isShowPreviewDialog = false">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </task-design-view>
</template>
<script>
  // @ is an alias to /src
  import { TaskDesignView } from '@/layouts';
  import iconConfig from './config/iconConfig';
  import draggable from 'vuedraggable';
  import form_list from './components/custom/FormList';
  import renders from './components/custom/Render';
  import inputWid from './components/widget/input';
  import { mapActions, mapGetters } from 'vuex';
  import { getDictionaryBySearch } from '@/api/task';

  export default {
    name: 'home',
    data() {
      return {
        isHaveFormData: false,
        iconConfig,
        form_list: form_list,
        list2: [],
        initForm: {},
        previewForm: {},
        modalFormData: {
          fieldNm: '',
          fieldHint: '',
          required: 1,
          print: 1,
          major: 1
        },
        currentItemIndex: -1,
        currentItemType: '',
        currentItemLabel: '',
        isFormShow: false,
        isShowPreviewDialog: false,
        isClickInner: false,
        templateName: this.$route.query.templateName,
        // 是否点击外部列表
        isHaveClickOut: false,
        formInnerIndex: 0,
        // 当前选中的明细的index
        currentParentIndex: 0,
        equipmentRangeList: []
      };
    },
    // provide() {
    //   return {
    //     isClickOut: this.$data
    //   }
    // },
    watch: {
      isShowPreviewDialog(val) {
        console.log(this.list2);
      }
    },
    components: {
      draggable,
      renders,
      TaskDesignView
      // 'Myinput': inputWid
    },
    mounted() {
      this.getFromData();
      /* this.getDictionaryBySearch(); */
    },
    methods: {
      ...mapActions(['saveWorkTemplateField']),
      /**
       * 父组件的上方导航条回调
       * @param val
       * @param callback
       */
      handleTitleChange(val, callback) {
        const data = this.saveForm();
        console.log(data);
        this.saveWorkTemplateField(data)
          .then(res => {
            // 跳转页面
            callback();
          });
      },
      // 预览
      preview() {
        this.isShowPreviewDialog = true;
      },
      // 获取表单数据
      getFromData() {
        console.log(this.createformData);
        // 编辑或者回显
        if (this.createformData.length !== 0) {
          this.createformData.forEach((item) => {
            console.log(item.expand);
            let expandObj = {};
            // try {
            //   expandObj = JSON.parse(item.expand)
            // }
            // catch(err) {
            //   expandObj = item.expand
            // }
            // 编辑而来的
            if (item.expand && item.expand.__proto__.constructor == String) {
              expandObj = JSON.parse(item.expand);
            } else {
              expandObj = item.expand;
            }
            const obj = Object.assign(item, expandObj);
            this.list2.push({
              obj: obj
            });
          });
        }
        console.log(this.list2);
      },
      // 保存
      saveForm() {
        const tempList = JSON.parse(JSON.stringify(this.list2));
        console.log(tempList);
        const keyArr = ['fieldNm', 'fieldTp', 'required', 'print', 'major', 'id', 'expand', 'obj', 'fieldId'];
        tempList.forEach((item, index) => {
          const expand = {};
          item.fieldOrder = index + 1;
          for (const key in item.obj) {
            if (!keyArr.includes(key)) {
              expand[key] = item.obj[key];
              delete item.obj[key];
            } else if (key !== 'obj') {
              item[key] = item.obj[key];
            }
          }
          delete item.obj;
          item.expand = expand;
        });
        return tempList;
      },
      startFun(evt) {
        console.log('start');
      },
      setId() {
        const str = Number(Number(Math.random().toString().substr(3, 30)) + Date.now()).toString(32);
        return 'formId' + str;
      },
      endFun(evt) {
        console.log(evt);
        const tempId = this.setId();
        this.list2[evt.newIndex]['obj']['id'] = tempId;
        this.list2[evt.newIndex]['obj']['fieldId'] = tempId;
        console.log('end');
        // setTimeout(()=>{
        //     this.list2[0].obj.fieldHint = 'haha'
        //     console.log(this.list2);
        // },3000)
      },
      onSubmit() {
        console.log(this.isHaveClickOut);
        if (!this.isHaveClickOut) {
          this.$bus.emit('renderFormInner', this.modalFormData, this.formInnerIndex, this.currentParentIndex);
        } else {
          console.log('ok');
          const data = this.list2[this.currentItemIndex].obj;
          const items = Object.keys(data);
          this.list2[this.currentItemIndex].obj = Object.assign({},
            this.list2[this.currentItemIndex].obj,
            this.modalFormData
          );
        }
      },
      changeInnerList(val, index) {
        console.log(val);
        console.log(index);
        this.list2[index]['obj']['fieldValue'] = val;
        console.log(this.list2);
      },
      selectFormInner(index, obj, listInner, parentIndex) {
        // 当点击内部列表之后防止表单渲染为detail的
        this.isClickInner = true;
        this.$bus.emit('clickOut', false);
        this.isHaveClickOut = false;
        this.formInnerIndex = index;
        this.currentParentIndex = parentIndex;
        console.log(parentIndex);
        // 初始化表单
        this.modalFormData = this.initForm;
        // 集合form配置项
        // this.modalFormData = Object.assign({},this.modalFormData,formConfig[obj.fieldTp])
        this.currentItemIndex = -1;
        this.currentItemLabel = obj.fieldNm;
        this.currentItemType = obj.fieldTp;
        this.modalFormData = Object.assign({},
          this.modalFormData,
          listInner[index].obj
        );
        console.log(this.modalFormData);
        this.isFormShow = true;
      },
      // 选中item
      selectForm(index, obj) {
        console.log(obj);
        // 当没有点击过内部列表时
        if (!this.isClickInner) {
          // 点击外部时应当把内部的选中状态取消
          console.log('waibu');
          this.$bus.emit('clickOut', true);
          this.isHaveClickOut = true;
          // 防止更改外部列表的配置项也会把内部的修改
          this.formInnerIndex = -1;
          // 初始化表单
          this.modalFormData = this.initForm;
          // 集合form配置项
          // this.modalFormData = Object.assign({},this.modalFormData,formConfig[obj.fieldTp])
          this.currentItemIndex = index;
          this.currentItemLabel = obj.fieldNm; // 没啥用变量
          this.currentItemType = obj.fieldTp; // 没啥用变量
          this.modalFormData = Object.assign({},
            this.modalFormData,
            this.list2[this.currentItemIndex].obj
          );
          console.log(this.modalFormData);
          this.isFormShow = true;
        }
        this.isClickInner = false;
      },
      // 删除克隆控件
      removeEle(index) {
        console.log(index);
        this.list2.splice(index, 1);
        if (this.list2.length === 0) {
          this.isFormShow = false;
        }
        this.currentItemIndex = -1;
      },
      handleChange() {
        console.log('sss');
      },
      // https://github.com/SortableJS/Vue.Draggable#clone
      // 克隆,深拷贝对象
      cloneData(original) {
        // 深拷贝对象，防止默认空对象被更改
        return JSON.parse(JSON.stringify(original));
      },
      // 控件回填数据
      handleChangeVal(val, element) {
        console.log(element);
        // this.$set(this.formData, element.obj.name, val);
      },
      changeValue() {
        console.log(111);
      },
      addItems(index) {
        const lengthValue = this.modalFormData.items.length + 1;
        this.modalFormData.items.splice(index, 0, { value: lengthValue, label: `选项内容` });
      },
      delItems(index) {
        console.log(index);
        this.modalFormData.items.splice(index, 1);
      },
      getDictionaryBySearch() {
        const data = {
          corpId: 6
        };
        getDictionaryBySearch(data)
          .then(res => {
            this.equipmentRangeList = res.data.rows;
            console.log(this.equipmentRangeList);
          });
      }
    },
    computed: {
      ...mapGetters([
        'createformData'
      ]),
      // 拖拽表单1
      dragOptions1() {
        return {
          animation: 500,
          ghostClass: 'ghost',
          disabled: false,
          // 分组
          group: {
            name: 'shared',
            pull: 'clone',
            revertClone: false
          },
          // 禁止拖动排序
          sort: false
        };
      },
      // 拖拽表单2
      dragOptions2() {
        return {
          animation: 0,
          ghostClass: 'ghost',
          group: {
            // 只允许放置shared的控件,禁止pull
            put: ['shared']
          }
        };
      }
    }
  };

</script>
<style lang="less" scoped>
  .form-list-group {
    display: flex;
    flex-wrap: wrap;
    padding: 20px 0 !important;
  }

  .createForm {
    border-radius: 4px;
    border: 1px solid rgba(143, 151, 165, 0.46);
    background-color: #fff;
    overflow: hidden;
    color: #303133;
    transition: .3s;

    .formTitle {
      font-size: 16px;
      color: gray;
      margin-left: 40px;
    }

    .tab {
      height: 30px;
      line-height: 40px;
      font-size: 20px;
      text-align: center;
    }
    & > .el-form-item__label {
      padding: 0px !important;
    }
  }

  .card {
    width: 46%;
    margin-right: 2%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-radius: 4px;
    border: 1px solid #ebeef5;
    background-color: #fff;
    overflow: hidden;
    height: 30px;
    line-height: 30px;
    padding-left: 15px;
    margin-bottom: 10px;

    .widgeticon {
      height: 20px;
      width: 20px;
      margin-right: 7px;
    }

  }

  .col {
    min-height: calc(100vh - 90px);
    background-color: white;
  }

  .cfc_main {
    display: flex;
    justify-content: center;
    height: 670px;
    width: 490px;
    min-width: 490px;
    max-width: 490px;
    position: relative;
    background: url("../../../../assets/phone.png");
    background-size: 100% 100%;
    background-repeat: no-repeat;

    .createFormCenter {
      position: absolute;
      overflow-x: hidden;
      overflow-y: auto;
      width: 292px;
      height: 480px;
      left: 50%;
      margin-left: -146px;
      top: 73px;
      max-height: 480px;
      background: #f6f6f6;

      .activeItem {
        border: 1px solid #38adff;
      }
    }
  }

  .col1 {
    min-height: calc(100vh - 90px);
    background-color: white;
    padding: 10px;
  }

  .disFlex {
    display: flex;
    align-items: baseline;
    width: 100%;
    background-color: white;
    border: 1px dashed transparent;

    &:not(:first-child) {
      margin-top: 10px;
    }
  }

  .el-date-editor.el-input, .el-date-editor.el-input__inner {
    width: 100% !important;
  }

  .el-form--label-top .el-form-item__label {
    padding: 0px !important;
  }

  .el-form-item {
    margin-bottom: 0px !important;
  }

  .task-design-content {
    position: fixed;
    top: 60px;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1;
    overflow-x: hidden;
    overflow-y: auto;
    padding-bottom: 30px;
  }

</style>
