<template>
  <div>
    <div class="mt-3" v-loading="loading">
      <div>
        <el-table
          :data="summarysListData.data"
          style="width: 100%"
          @selection-change="handleSelectSummarys"
          :height="summaryTableHeight"
        >
          <el-table-column
            prop="name"
            :label="$t('form.abstract_title')"
            min-width="45%"
          >
            <template slot-scope="scope">
              <span @click="onRowClickSummarys(scope.row)">{{
                scope.row.name
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop
            :label="$t('form.abstract_type')"
            min-width="45%"
          >
            <template slot-scope="scope">
              <span v-show="scope.row.scope == 0">{{
                $t('form.pending')
              }}</span>
              <span v-show="scope.row.scope == 1">{{
                $t('form.flow_notice')
              }}</span>
              <span v-show="scope.row.scope == 6">{{
                $t('form.flow_cc')
              }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('form.op')" min-width="150px">
            <template slot-scope="scope">
              <i
                class="el-icon-delete"
                style=""
                @click="showDeleteConfirmSummarys(scope.row.id)"
              ></i>
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" class="green d-font-size">
            *{{$t('view.usein_flow')}}
          </el-row>
        <el-row class="fc" style="height: 48px">
          <el-button
            type="primary"
            plain
            size="mini"
            @click="showSummarysDialog"
            >{{ $t('btns.create') }}</el-button
          >
        </el-row>
      </div>
    </div>
    <!-- 摘要 -->
    <el-dialog
      :title="$t('form.add_abstract')"
      :visible.sync="summarysVislble"
      width="80%"
      :before-close="handleSummarysClose"
      :append-to-body="true"
    >
      <span>
        <div>
          <el-form
            label-position="top"
            label-width="80px"
            :model="summarysParams"
            ref="summarysParams"
            :rules="summarysRules"
          >
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item :label="$t('form.abstract_title')" prop="title">
                  <el-input
                    v-model="summarysParams.title"
                    size="small"
                    :placeholder="$t('placeholder.title')"
                  ></el-input>
                </el-form-item>
                <el-form-item :label="$t('form.abstract_type')">
                  <el-select
                    v-model="summarysParams.scope"
                    :placeholder="$t('placeholder.select')"
                    size="small"
                  >
                    <el-option
                      :label="$t('form.pending')"
                      :value="0"
                    ></el-option>
                    <el-option
                      :label="$t('form.flow_notice')"
                      :value="1"
                    ></el-option>
                    <el-option
                      :label="$t('form.flow_cc')"
                      :value="6"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item :label="$t('form.showTag')">
                  <el-radio v-model="summarysParams.isShowTags" :label="1">{{
                    $t('form.yes')
                  }}</el-radio>
                  <el-radio v-model="summarysParams.isShowTags" :label="0">{{
                    $t('form.no')
                  }}</el-radio>
                </el-form-item>
              </el-col>
              <el-col :span="16">
                <el-form-item :label="$t('form.type')">
                  <el-radio-group
                    v-model="summarysParams.type"
                    @change="onChangeType"
                  >
                    <el-radio label="00">{{ $t('form.design') }}</el-radio>
                    <el-radio label="01">{{ $t('form.script') }}</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-transfer
                  v-model="fieldNames"
                  :data="summarysData"
                  @change="onChangeFieldNames"
                  v-if="designVislble"
                ></el-transfer>
                <el-form-item :label="$t('form.script')" v-if="!designVislble">
                  <el-input
                    type="textarea"
                    :rows="6"
                    v-model="summarysParams.summaryScript"
                    size="small"
                    :placeholder="$t('placeholder.script')"
                    style="width: 95%"
                  ></el-input>
                  <i
                    class="el-icon-edit-outline"
                    style="width: 5%"
                    @click="showScriptEditor('summaryScript')"
                  ></i>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button plain size="small" @click="handleSummarysClose">{{
          $t('btns.cancel')
        }}</el-button>
        <el-button
          type="primary"
          size="small"
          @click="saveSummarys('summarysParams')"
          :loading="btnLoading"
          >{{ $t('btns.save') }}</el-button
        >
      </span>
         <!-- 脚本选择器弹窗 -->
    <!-- scriptEditorVisible:弹窗显示   showScritptEditorCode：将文本框的值传给编译器  handleScriptEditor：将编译器的值传给textarea-->
    <ScriptEditorSelect
      v-if="scriptEditorVisible"
      :scriptEditorVisible="scriptEditorVisible"
      :editorCode="showScritptEditorCode"
      @closeScriptEditorDialog="scriptEditorVisible = false"
      @saveScriptEditor="handleScriptEditor"
      :isNested="true"
    />
    </el-dialog>
    
  </div>
  
</template>

<script>
import {
  getSummarysListData,
  deleteSummarys,
  getFormValueStoreFields,
  createSummarys,
  updateSummarys,
} from '@/service/FormApi.js'
import { nameCheck } from '@/utils/utils.js'
import {delMsg} from '@/utils/elementui'
import ScriptEditorSelect from '@/components/Common/scriptEditor'
export default {
  name: 'FormMapping',
  props: {
    formId: String,
    moduleId: String,
  },
  components:{
    ScriptEditorSelect
  },
  data() {
    return {
      loading: false,
      summarysData: [],
      summarysListData: [],
      summarysVislble: false, //摘要对话框
      summarysParams: {
        appId: '',
        moduleId: '',
        id: '', //摘要id
        name: '', //摘要名称
        type: '00',
        isShowTags: 0,
        title: '', //摘要标题
        uri: '',
        fieldNames: '',
        summaryScript: '',
        scope: 0, //摘要类型(1:流程通知、分享,6:流程抄送,0:待办摘要)
        formId: '', // 表单id
        formName: '',
        parentId: '',
      },
      summarysRules: {
        title: [
          { required: true, message: this.$t('placeholder.title'), trigger: 'blur' },
          { validator: nameCheck, trigger: 'blur' },
        ],
      },
      multipleSelectionSummarysArray: [],
      multipleSelectionSummarysId: [],
      fieldNames: [],

      designVislble: true, // 设计模式
      btnLoading: false, // 按钮加载的图标
      scriptEditorVisible: false, // 脚本编辑器弹窗
      currentScriptEditor: '', // 当前点击的是哪一个脚本编辑器
    }
  },
  methods: {
       /**
     * 显示脚本编辑器弹框
     */
    showScriptEditor(val) {
      this.scriptEditorVisible = true
      this.currentScriptEditor = val
    },
     /**
     * 将脚本编辑器的值写入到textarea中
     */
    handleScriptEditor(val) {
       if (this.currentScriptEditor === 'summaryScript') {
        // 流程启动脚本
        this.summarysParams.summaryScript=val
      }
    },

    /**
     * 获取摘要列表
     */
    getSummarysListData() {
      let params = {
        appId: sessionStorage.getItem('appId'),
        id: this.formId,
      }
      this.loading = true
      getSummarysListData(params, {
        onSucess: (response) => {
          if (response.data.errcode == 0) {
            this.summarysListData = response.data.data
            this.loading = false
          }
        },
      })
    },

    /**
     * 勾选行时响应-摘要列表
     */
    handleSelectSummarys(val) {
      let multipleSelectionSummarysId = []
      if (val.length) {
        val.map((e) => {
          multipleSelectionSummarysId.push(e.id)
        })
      }
      this.multipleSelectionSummarysArray = val
      this.multipleSelectionSummarysId = multipleSelectionSummarysId
    },

    /**
     * 批量删除操作
     */
    async showDeleteConfirmSummarys(val) {
      try{
        await delMsg(this.$t('msg.delConfirm'), this.$t('msg.tip'))
        const response = await deleteSummarys([val])
        if (response.data.errcode == 0) {
          this.getSummarysListData()
          this.$message.success(this.$t('msg.del_ss'))
        }
      }catch(e){
        console.log(e)
      }
    },

    /**
     * 显示摘要对话框
     */
    showSummarysDialog() {
      this.getFormValueStoreFields()
      this.summarysVislble = true
    },

    /**
     * 隐藏摘要对话框
     */
    handleSummarysClose() {
      let summarysParams = {
        ...this.summarysParams,
        id: '', //摘要id
        name: '', //摘要名称
        type: '00',
        isShowTags: 0, // 显示html标签
        title: '', //摘要标题
        uri: '',
        fieldNames: '',
        summaryScript: '',
        scope: 1, //摘要类型(1:流程通知、分享,6:流程抄送,0:待办摘要)
      }
      this.fieldNames = []
      this.summarysParams = summarysParams
      this.summarysVislble = false
      this.designVislble = true
    },

    /**
     * 新建或更新摘要
     */
    saveSummarys(summarysParams) {
      this.$refs[summarysParams].validate(async (valid) => {
        if (valid) {
          if ( this.summarysParams.type == '00' && this.summarysParams.fieldNames == '') {
            this.$message.error(this.$t('msg.cannot_empty'))
            return false
          }

          if(this.summarysParams.id){
            this.btnLoading = true;
            const response = await updateSummarys(this.summarysParams)
            this.btnLoading = false;
            if (response.data.errcode == 0) {
              this.$message.success(this.$t('msg.update_ss'))
              this.getSummarysListData()
              this.handleSummarysClose()
            }
          }else{
            this.btnLoading = true;
            const response = await createSummarys(this.summarysParams)
            this.btnLoading = false;
            if (response.data.errcode == 0) {
              let summarysParams = {
                ...this.summarysParams,
                id: response.data.data.id,
              }
              this.summarysParams = summarysParams
              this.getSummarysListData()
              this.handleSummarysClose()
              this.$message.success(this.$t('msg.created_ss'))
            }
          }
        } else {
          return false
        }
      })
    },

    /**
     * 编辑摘要
     */
    onRowClickSummarys(row) {
      if (row.type == '00') {
        this.designVislble = true
      } else {
        this.designVislble = false
      }
      let summarysParams = {
        ...this.summarysParams,
        ...row
      }
      // 兼容旧数据以分号拼接
      this.fieldNames = row.fieldNames
        ? row.fieldNames.includes(';')
          ? row.fieldNames.split(';')
          : row.fieldNames.split(',')
        : []
      this.getFormValueStoreFields()
      this.summarysParams = summarysParams
      this.showSummarysDialog()
    },

    /**
     * 获取类型-设计-表单字段值
     */
    onChangeFieldNames(val) {
      let fieldNames = val.join(';')
      let summarysParams = {
        ...this.summarysParams,
        fieldNames: fieldNames,
      }
      this.summarysParams = summarysParams
    },

    /**
     * 类型-设计、脚本
     */
    onChangeType(val) {
      if (val == '00') {
        this.designVislble = true
      } else {
        this.designVislble = false
      }
    },

    /**
     * 获取数据来源表单字段
     */
    getFormValueStoreFields() {
      let params = {
        id: this.formId,
      }
      getFormValueStoreFields(params, {
        onSucess: (response) => {
          if (response.data.errcode == 0) {
            this.generateData(response.data.data)
          }
        },
      })
    },

    /**
     * 处理数据来源表单字段
     */
    generateData(datas) {
      let data = []
      if (datas) {
        for (let key in datas) {
          let obj = {}
          obj.label = datas[key]
          obj.key = key
          if (obj.key !== '') {
            data.push(obj)
          }
        }
        this.summarysData = data
      }
    },
  },
  mounted() {
    this.summarysParams = {
      ...this.summarysParams,
      appId: sessionStorage.getItem('appId'),
      moduleId: this.moduleId,
      formId: this.formId,
      parentId: this.formId,
    }
    this.getSummarysListData()
  },
  computed: {
    /**
     * 计算摘要的table高度
     */
    summaryTableHeight() {
      if (this.summarysListData.data) {
        if ((this.summarysListData.data.length + 1) * 48 > this.operaHeight) {
          return this.operaHeight
        } else {
          return (this.summarysListData.data.length + 1) * 48
        }
      } else {
        return 100
      }
    },
     /**
     * 脚本编辑器的值
     */
    showScritptEditorCode() {
      let code=this.summarysParams.summaryScript
      return code
    }
  },
}
</script>
<style lang='less' scoped>
</style>