<template>
  <el-container class="fullheight base-setting">
    <el-form
      v-model="dataTemplate"
      class="base-setting-form"
      data-vv-scope="editDataTemplateForm"
      v-form="{formItemAlign: 'left', inputsDisplay: 'block'}"
    >
      <div class="base-form__wrap">
        <h3 class="base-form__title">表单信息</h3>
        <div class="base-form__info">
          <ht-form-item label="表单别名" prop="formKey" label-width="128px">
            <ht-input
              v-model="dataTemplate.formKey"
              disabled
              :validate="{required: true}"
            ></ht-input>
          </ht-form-item>
          <ht-form-item label="报表名称" prop="name" label-width="128px">
            <ht-input
              v-model="dataTemplate.name"
              :validate="{required: true}"
              :maxlength="50"
              :showWordLimit="true"
            >
              <el-button
                icon="icon-guojihua"
                slot="append"
                style="width: 50px"
                @click="editI18nMessage('')"
              ></el-button>
            </ht-input>
          </ht-form-item>
          <ht-form-item label="报表别名" prop="alias" label-width="128px">
            <ht-input
              v-model="dataTemplate.alias"
              :disabled="!isEditable"
              v-pinyin="dataTemplate.name"
              name="dataAlias"
              :validate="{
                required: true,
                regex: {
                  exp: '^[a-zA-Z][a-zA-Z0-9_]*$',
                  message: '只能输入字母、数字、下划线，且以字母开头'
                }
              }"
              :maxlength="50"
              :showWordLimit="true"
            ></ht-input>
          </ht-form-item>
          <ht-form-item
            label="报表分类"
            class="is-required report-classify"
            label-width="128px"
          >
            <eip-sys-type-selector
              key="baseFormSetting"
              v-model="dataTemplate.typeName"
              cat-id="7"
              :sys-type-id.sync="dataTemplate.typeId"
            ></eip-sys-type-selector>
          </ht-form-item>
          <ht-form-item label="绑定流程" prop="subject" label-width="128px">
            <span :class="{'select-flow': dataTemplate.subject}">{{
              dataTemplate.subject
            }}</span>
            <div
              class="button-wrap"
              :class="{'left-padding': dataTemplate.subject}"
            >
              <el-button type="text" size="mini" @click="showFormFlowDialog()"
                >选择</el-button
              >
              <el-button
                v-if="dataTemplate.defId"
                type="text"
                size="mini"
                @click="clearFormFlow()"
                >清除</el-button
              >
            </div>
            <form-flow-dialog
              ref="formFlowDialog"
              :boCode="dataTemplate.boDefAlias"
              :formKey="dataTemplate.formKey"
              :single="true"
              @onConfirm="formFlowDialogOnConfirm"
              append-to-body
            />
          </ht-form-item>

          <ht-form-item
            label="绑定手机端表单"
            prop="mobileFormName"
            label-width="128px"
          >
            <template slot="label">
              <el-tooltip
                content="手机表单用于扫描二维码后,手机端的查看页面,配置了生成二维码按钮,必须配置手机表单"
              >
                <i class="property-tip icon-question" />
              </el-tooltip>
              <span>绑定手机端表单</span>
            </template>

            <span :class="{'select-flow': dataTemplate.mobileFormName}">{{
              dataTemplate.mobileFormName
            }}</span>
            <div
              class="button-wrap"
              :class="{'left-padding': dataTemplate.mobileFormName}"
            >
              <el-button type="text" size="mini" @click="selectMobileForm()"
                >选择</el-button
              >
              <el-button
                v-if="dataTemplate.mobileFormAlias"
                type="text"
                size="mini"
                @click="clearMobileForm()"
                >清除</el-button
              >
            </div>
            <EipFormDialog
              ref="eipFormDialog"
              :single="true"
              @onConfirm="dialogConfirm"
              formType="mobile"
              appendToBody
              :pcFormKey="dataTemplate.formKey"
            />
          </ht-form-item>
        </div>
      </div>
      <div class="base-form__wrap form-setting">
        <h3 class="base-form__title">表单设置</h3>
        <div class="base-form__info">
          <ht-form-item label="是否分页" prop="needPage" label-width="128px">
            <ht-radio
              v-model="dataTemplate.needPage"
              :options="[
                {key: 1, value: '分页'},
                {key: 2, value: '不分页'}
              ]"
              :validate="{required: true}"
            />
          </ht-form-item>

          <ht-form-item
            v-if="dataTemplate.needPage == 1"
            label="默认分页大小"
            label-width="128px"
          >
            <ht-select
              v-model="dataTemplate.pageSize"
              :options="[
                {key: 10, value: 10},
                {key: 20, value: 20},
                {key: 50, value: 50},
                {key: 100, value: 100},
                {key: 200, value: 200},
                {key: 300, value: 300}
              ]"
              :validate="{required: true}"
            />
          </ht-form-item>

          <ht-form-item label="是否需要初始化模板" label-width="158px">
            <ht-select
              v-model="dataTemplate.resetTemp"
              :options="[
                {key: 1, value: '是'},
                {key: 0, value: '否'}
              ]"
              :validate="{required: true}"
            />
          </ht-form-item>

          <ht-form-item
            label="是否允许外链"
            prop="allowShare"
            label-width="128px"
          >
            <ht-radio
              v-model="dataTemplate.allowShare"
              :options="[
                {key: 1, value: '是'},
                {key: 2, value: '否'}
              ]"
              :validate="{required: true}"
            />
          </ht-form-item>

          <ht-form-item label="pc端数据模板" label-width="128px">
            <ht-select
              v-model="dataTemplate.templateAlias"
              class="m-r"
              :options="templates"
              :props="{key: 'alias', value: 'templateName'}"
              :validate="{required: true}"
            />
          </ht-form-item>
          <ht-form-item 
            label="移动端数据模板" 
            label-width="128px" 
            v-if="dataTemplate.mobileFormName"
          >
            <ht-select
              v-model="dataTemplate.mobileTemplateAlias"
              class="m-r"
              :options="mobileTemplates"
              :props="{key: 'alias', value: 'templateName'}"
              :validate="{required: true}"
            />
          </ht-form-item>
          
        

        </div>

        <ht-form-item 
            label="页内按钮" 
            label-width="128px" 
          >
           <template slot="label">
            <el-tooltip
              content="拖动调整按钮顺序,点击按钮名称编辑按钮"
            >
              <i class="property-tip icon-question" />
            </el-tooltip>
            <span>页内按钮</span>
          </template>

          <div> 
           <ht-tree
              ref="displaySettingTree1"
              node-key="id"
              :data="innerPageBtns"
              default-expand-all
              :expand-on-click-node="false"
              draggable
              :allow-drop="allowDrop"
              :props="{label: 'desc', children: 'children'}"
              :isShowrefresh="false"
              class="inner-btn-list"
            >

             <li class="custom-tree-node" slot-scope="{node, data}">  
              <el-checkbox v-model="data.show" style="margin-right: 10px;" v-if="data.init"></el-checkbox> 
              <el-button v-else type="text" icon="el-icon-delete" @click="delInnerBtn(node)"></el-button>
              <el-button size="mini" style="margin-right: 20px;" @click="editInnerBtn(node)" :type="data.type">{{data.name}}</el-button>
            </li> 
          </ht-tree>
          <el-button size="mini" style="position:relative;"  type="primary" icon="el-icon-plus" @click="addInnerBtn()"></el-button>
          </div>
        </ht-form-item>

        <ht-form-item
          label="前置groovy脚本"
          prop="beforeScript"
          label-width="128px"
          class="script-form-item"
        >
          <div class="tip-message">
            获取表单主表子表内容，例:&nbsp;boData.getByKey("字段名");&nbsp;给表单主表内容赋值，例:&nbsp;boData.set("字段名","值");
            给表单子表内容赋值，例:&nbsp;boData.getSubMap().get("子表名").get(第几行).set("字段名","值");
          </div>
          <HtMonacoEditor ref="mycodeBefore" v-model="dataTemplate.beforeScript" height="300px"/>

        </ht-form-item>
        <ht-form-item
          label="后置groovy脚本"
          prop="afterScript"
          label-width="128px"
          class="script-form-item"
        >
          <HtMonacoEditor ref="mycodeAfter" v-model="dataTemplate.afterScript" height="300px"/>
        </ht-form-item>
      </div>
    </el-form>
    <!-- 编辑报表模板对话框  -->
    <template-html-edit
      ref="templateHtmlEdit"
      name="templateHtmlEdit"
      :data="dataTemplate"
      append-to-body
    />

    <!-- 报表添加到菜单对话框  -->
    <template-add-to-menu
      ref="templateAddToMenu"
      name="templateAddToMenu"
      :alias="dataTemplate.alias"
      append-to-body
    />
    <i18n-message-edit
      ref="i18nMessageEdit"
      :messageKey="i18nMessageKey"
      @after-save="afterSaveI18n"
    />

    <el-dialog
      :title="isEidtBtn?'编辑按钮':'新增按钮'"
      :visible.sync="innerBtnDialogVisible"
      append-to-body
      v-if="innerBtnDialogVisible"
      :close-on-click-modal="false"
      width="70%">
  
     <div style="margin-top: 0px; margin-bottom: 15px">
       <div style="margin-bottom: 10px">
        按钮名称: <ht-input  permission="b" :maxlength="10" :show-word-limit="true" v-model="innerBtnObj.name"/>
      </div>

      <div style="margin-bottom: 10px">
        按钮类型: <el-tag :type="innerBtnObj.type" :style="{margin: '0 20px',border: 'none', color: !innerBtnObj.type ? 'black':''}">{{innerBtnObj.type ? btnTypes.filter((b)=> b.type == innerBtnObj.type)[0].name : '默认'}}</el-tag> 
        <el-button size="mini" :type="type.type" v-for="type in btnTypes" :key="type.type" @click="innerBtnObj.type = type.type" >{{type.name}}</el-button>
      </div>
        <code v-if="!innerBtnObj.init">
          <code>
            <span style="color: red; margin-left: 15px"
              >javascript脚本,在点击按钮时触发，参数：_req用来请求后台的
              ,_data当前表单的数据,_this当前表单this对象</span
            >
            <br />
            <span style="color: red; margin-left: 15px">
              使用http请求后台接口地址的方法 this.$http.get(url).then(res => {
              }) ,使用_req请求后台接口地址的方法 _req(url, data, options).then(res
              => { })
            </span>
            <br />
  
            <span style="color: red; margin-left: 15px"
              >跳转url可以使用通用方法 _this.commonOpenUrl(url)</span
            >
            <br />
            <span style="color: red; margin-left: 15px" > 
               例如:根据表单某个字段的值，调用后台接口，转化成拼音并赋值到另一个字段
            </span>
            <br />
            <span style="color: red; margin-left: 15px" > 
               _req(window.context.form+`/base/tools/v1/getPinyin?chinese=${_data.cs111111.zd1}`).then((resp) => {
            </span>
             <br />
            <span style="color: red; margin-left: 30px">  _data.cs111111.zd2 = resp.data.value</span >
            <br />
            <span style="color: red; margin-left: 15px" > })</span >

          </code>
        </code>
      </div>
      <div style="margin-bottom: 10px" v-if="!innerBtnObj.init">
        表单变量:
        <el-select
          value-key="name"
          v-model="formVar"
          clearable
          @change="diyScriptChange"
        >
          <el-option-group
            v-for="group in formVariables"
            :key="group.name"
            :label="group.desc"
          >
            <el-option
              v-for="item in group.fields"
              :key="item.path"
              :label="item.desc"
              :value="item.path"
            >
              <span style="float: left">{{
                item.desc + '(' + item.path + ')'
              }}</span>
            </el-option>
          </el-option-group>
        </el-select><span style="color: red;">子表和孙表是以数组存放的，需要根据数组下标来取值。孙表示例：_data.bo别名.sub_子表建模名[下标].sub_孙表建模名[下标].孙表字段名</span>
      </div>
      <div style="width: 100%; height: 100%" v-if="!innerBtnObj.init">
        <HtMonacoEditor ref="btnDiyJs" v-model="innerBtnObj.diyJs" height="300px"/>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="innerBtnDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="innerBtnConfirm">确 定</el-button>
      </span>
    </el-dialog>

  </el-container>
  
</template>

<script>
const FormFlowDialog = () =>
  import('@/components/form/dataTemplate/FormFlowDialog.vue')
const TemplateHtmlEdit = () =>
  import('@/components/form/dataTemplate/TemplateHtmlEdit.vue')
const TemplateAddToMenu = () =>
  import('@/components/form/dataTemplate/TemplateAddToMenu.vue')

const EipFormDialog = () => import('@/components/dialog/EipFormDialog.vue')

import utils from '@/hotent-ui-util.js'
import 'codemirror/addon/display/autorefresh'
import i18nMessageEdit from '@/components/system/I18nMessageEdit.vue'
import EipSysTypeSelector from '@/components/selector/EipSysTypeSelector.vue'
import {mapState} from 'vuex'

const btnTypes = [{name:'默认',type:''},{name:'主要',type:'primary'},{name:'成功',type:'success'},
                  {name:'信息',type:'info'},{name:'警告',type:'warning'},{name:'危险',type:'danger',color:'#dd6161'}]

export default {
  name: 'base-setting',
  props: ['data', 'focusAlias', 'showShareBtn'],
  components: {
    FormFlowDialog,
    TemplateHtmlEdit,
    TemplateAddToMenu,
    EipFormDialog,
    i18nMessageEdit,
    EipSysTypeSelector
  },
  data() {
    return {
      dataTemplate: {alias: ''},
      templates: [],
      mobileTemplates:[],
      isEditable: true,
      cmOptions1: {
        value: '',
        mode: 'groovy',
        readOnly: false,
        smartIndent: true,
        tabSize: 1,
        theme: 'base16-light',
        lineNumbers: true,
        line: true,
        lineWrapping: true,
        autoRefresh: true
      },
      cmOptions2: {
        value: '',
        mode: 'groovy',
        readOnly: false,
        smartIndent: true,
        tabSize: 1,
        theme: 'base16-light',
        lineNumbers: true,
        line: true,
        lineWrapping: true,
        autoRefresh: true
      },
      i18nMessageKey: '',
      initInnerPageBtns:[{init:1,name:'保存',alias:'save',show:true, type:"primary"},
                     {init:1,name:'打印',alias:'print',show:true},
                     {init:1,name:'返回',alias:'back',show:true}],
      innerPageBtns:[],
      innerBtnDialogVisible: false,
      innerBtnObj:{}, // 正在编辑或者新增的按钮对象
      isEidtBtn: false, // 是否编辑按钮
      formVar:'',
      btnTypes:btnTypes
    }
  },
  computed: mapState( {
    templateNames() {
      return this.templates.map(item=>item.templateName).join(',') 
    },
    formVariables(state) {
      return state.form.formListCommonVar.map(item => {
        return {
          ...item,
          fields: item.fields.filter((f)=> f.oldTableField).map(it => {
            let fieldName = '_data.'+this.dataTemplate.boDefAlias+'.'+it.name
            if (item.type=='sub' || item.type=='sun') {
              fieldName = '_data.'+this.dataTemplate.boDefAlias+'.sub_'+item.name.replace('W_','').toLowerCase()+'[0].'
              if (it.name.startsWith('F_')) {
                fieldName+=it.name.replace('F_','')
              }else{
                fieldName+=it.name
              }
            }
            return {
              ...it,
              path: fieldName
            }
          })
        }
      }).filter(item => item.type != 'join')
    }
  }),
  mounted() {
    this.dataTemplate = this.data.bpmDataTemplate
    this.dataTemplate.beforeScript = this.dataTemplate.beforeScript || ''
    this.dataTemplate.afterScript = this.dataTemplate.afterScript || ''
    this.templates = this.data.templates
    this.mobileTemplates = this.data.mobileTemplates
    this.dataTemplate.templateAlias =
      this.templates[0] && this.templates[0].alias
    this.dataTemplate.mobileTemplateAlias =this.mobileTemplates&& this.mobileTemplates[0] && this.mobileTemplates[0].alias
    this.initData()
  },
  watch: {
    focusAlias: function(newVal, oldVal) {
      if (newVal) {
        document.getElementsByName('dataAlias')[0].focus()
        document.getElementsByName('dataAlias')[0].style.border =
          '1px solid red'
      } else {
        document.getElementsByName('dataAlias')[0].style.border = ''
      }
    },
    'dataTemplate.allowShare': function(newVal, oldVal) {
      if (newVal) {
        this.$emit('update:showShareBtn', newVal)
      }
    },
    'dataTemplate.defId': function(newVal) {
      let sql = ''
      if (
        this.data.bpmDataTemplate.joinTablesSql &&
        this.data.bpmDataTemplate.joinTablesSql.trim() !== ''
      ) {
        sql = this.data.bpmDataTemplate.joinTablesSql
      } else {
        sql = `select * from ${this.data.fields[0].name}`
      }
      let params = {
        sql:
          this.data.bpmDataTemplate.joinTablesSql ||
          `select * from ${this.data.fields[0].name}`,
        dsName: this.data.bpmDataTemplate.dsName,
        formKey: this.data.bpmDataTemplate.formKey,
        instKey: !!newVal
      }
      this.$store.dispatch('form/setFormListCommonVar', params)
    },
    'dataTemplate.mobileFormName':{
      handler(val){
        if(val){
          this.dataTemplate.mobileTemplateAlias = this.mobileTemplates&& this.mobileTemplates[0] && this.mobileTemplates[0].alias
        }
      }
    }
  },
  methods: {
    diyScriptChange(myValue) {
       this.$refs.btnDiyJs.insertValue(myValue)
    },
    innerBtnConfirm(){
      if(!this.innerBtnObj.name){
        this.$message.error('按钮名称不能为空')
        return;
      }

      if(!this.innerBtnObj.init && !this.innerBtnObj.diyJs){
        this.$message.error('按钮脚本不能为空')
        return;
      }

      if (this.isEidtBtn) {
        for (let index = 0; index < this.innerPageBtns.length; index++) {
          const b = this.innerPageBtns[index];
          if (b.alias == this.innerBtnObj.alias) {
            this.innerPageBtns.splice(index,1,this.innerBtnObj)
            break;
          }
        }
      }else{
        this.innerBtnObj.alias = utils.uuid()
        this.innerPageBtns.push(this.innerBtnObj)
      }
      this.innerBtnDialogVisible = false
    },
    addInnerBtn(){
      this.innerBtnObj = {name:"",divJs:"",type:"",show:true};
      this.isEidtBtn= false
      this.innerBtnDialogVisible = true;
    },
    delInnerBtn(node){
      this.$confirm('是否确认删除此按钮？', '提示')
      .then(() => {
        for (let index = 0; index < this.innerPageBtns.length; index++) {
          const b = this.innerPageBtns[index];
          if (b.alias == node.data.alias) {
            this.innerPageBtns.splice(index,1)
            break;
          }
        }
      })
      .catch(() => {})
    },
    editInnerBtn(node){
      if (!node.data.type) {
        node.data.type = ''
      }
      this.isEidtBtn = true
      this.innerBtnObj = JSON.parse(JSON.stringify(node.data))
      this.innerBtnDialogVisible = true
    },
    allowDrop(draggingNode, dropNode, type) {
      // 是否允许放下
      // 字段不能移动到字段下
      if (dropNode.data && type == 'inner') {
        return false
      }
      return true
    },

    clearMobileForm() {
      this.dataTemplate.mobileFormAlias = ''
      this.dataTemplate.mobileFormName = ''
    },
    selectMobileForm() {
      this.$refs.eipFormDialog.showDialog()
    },
    dialogConfirm(data) {
      if (data && data.length > 0) {
        data = data[0]
        this.dataTemplate.mobileFormAlias = data.formKey
        this.dataTemplate.mobileFormName = data.name
      }
    },
    //初始化处理
    initData() {
      if (this.dataTemplate.id) {
        this.isEditable = false
      }
      if (this.dataTemplate.needPage === null) {
        this.dataTemplate.needPage = 1
        if (this.dataTemplate.pageSize == null) {
          this.dataTemplate.pageSize = 20
        }
      }
      if (this.dataTemplate.allowShare == null) {
        this.dataTemplate.allowShare = 2
      }
      if (this.dataTemplate.resetTemp == null) {
        this.$set(this.dataTemplate, 'resetTemp', 1)
      }

      if (this.dataTemplate.innerBtnConfig) {
        this.innerPageBtns =  JSON.parse(Base64.decode(this.dataTemplate.innerBtnConfig))
      }else{
        this.innerPageBtns =JSON.parse(JSON.stringify(this.initInnerPageBtns))
      }
    },
    //显示流程选择器
    showFormFlowDialog() {
      this.$refs.formFlowDialog.showDialog({})
    },
    //回填绑定流程
    formFlowDialogOnConfirm(selection) {
      if (!selection || selection.length == 0) {
        this.dataTemplate.defId = ''
        this.dataTemplate.subject = ''
      } else {
        this.dataTemplate.defId = selection[0].defKey
        this.dataTemplate.subject = selection[0].name
      }
    },
    //显示模板编辑器
    showHtmlEditDialog() {
      this.$refs.templateHtmlEdit.showDialog({})
    },
    //显示添加到菜单dialog
    showAddToMenuDialog(type) {
      this.$refs.templateAddToMenu.showDialog(type, 'addReport')
    },
    //清除绑定流程
    clearFormFlow() {
      this.dataTemplate.defId = ''
      this.dataTemplate.subject = ''
    },
    validateForm(callback) {
      this.dataTemplate.innerBtnConfig = Base64.encode(JSON.stringify(this.innerPageBtns))
      utils
        .validateForm(this, 'editDataTemplateForm')
        .then(r => {
          callback()
        })
        .catch(items => {
          this.$message.error(`请完整填写报表基本信息。`)
        })
    },
    /**
     * 国际化配置
     */
    editI18nMessage(after) {
      this.i18nMessageKey = `formTemplate.${this.dataTemplate.alias}`
      if (this.i18nMessageKey && after) {
        this.i18nMessageKey += after
      }
      this.$refs.i18nMessageEdit.handleOpen()
    },
    afterSaveI18n(data) {
      //保存后做一些数据处理
      data.key = data.key.replace('$', '#')
      this.dataTemplate.desc = data.key
      this.dataTemplate.desc_zh = data.desc
    }
  },

  created() {
    this.$validator = this.$root.$validator
  }
}
</script>
<style lang="scss" scoped>
.base-setting {
  padding-top: 9px;
  .base-setting-form {
    width: 100%;
    ::v-deep {
      .base-form__wrap {
        width: calc(100% - 122px);
        padding-left: 40px;
        padding-right: 80px;
        border: 1px solid #e6e6e6;
        .base-form__title {
          margin: 0;
          padding: 24px 0;
          font-size: 16px;
          color: #333;
          font-weight: bold;
        }
        .base-form__info {
          display: flex;
          flex-wrap: wrap;
          .el-form-item {
            width: calc(33.33% - 24px);
            margin-bottom: 32px;
            margin-right: 24px;
            .el-form-item__content {
              display: flex;
              .ht-form-inputs__block {
                width: 80%;
              }
            }
            .el-button--text {
              font-size: 14px;
            }
          }
          .select-flow {
            display: inline-block;
            width: 300px;
            height: 32px;
            line-height: 32px;
            background: rgba(243, 243, 243, 0.39);
            border-radius: 2px;
            color: #333;
            padding-left: 10px;
          }
          .button-wrap {
            display: inline-flex;
          }
          .left-padding {
            padding-left: 8px;
          }
        }
        .el-form-item__label {
          color: #888;
        }
      }
      .form-setting {
        margin-top: 40px;
        .script-form-item {
          width: 100%;
          margin-bottom: 32px;
          .tip-message {
            height: 40px;
            line-height: 40px;
            color: #ffae44;
            font-size: 14px;
            padding-left: 16px;
            margin-bottom: 12px;
            background: rgba(255, 174, 68, 0.1);
          }
        }
      }
    }
    .report-classify {
      ::v-deep {
        .el-form-item__content {
          .inputs {
            width: 100%;
          }
        }
      }
    }
  }
}
div/deep/.CodeMirror {
  font-family: monospace;
  height: 250px !important;
  color: black;
  direction: ltr;
}
/deep/ .el-scrollbar__wrap {
  overflow-x: hidden;
}

/deep/.el-tree-node__content > li {
  cursor: move;
}
/deep/.el-tree-node__content:hover {
 background: #fff
 ;
}

.inner-btn-list, .inner-btn-list /deep/ .el-tree-node{
  display: inline-block;
}

.inner-btn-list /deep/ .el-tree__wrapper{
  top: 9px;
}

/deep/.el-tree-node__expand-icon {
  display: none;
}



</style>
