<template>
  <div>
    <el-dialog
      :title="
        formData.type == 'addFlow'
          ? '新增流程'
          : formData.type === 'addData'
          ? '新增数据'
          : '查询数据'
      "
      :visible.sync="dialogVisible"
      width="55%"
      appendToBody
      :close-on-click-modal="false"
      :before-close="handleClose"
      top="8vh"
      v-if="dialogVisible"
    >
      <el-form ref="form" :model="formData" data-vv-scope="flowFormAddObj">
        <ht-form-item label="选择流程" v-if="formData.type === 'addFlow'">
          <ht-readonly-input v-model="formData.flow.name" />
          <el-button-group style="margin-left:5px">
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="showEipFlowDialog"
              >选择</el-button
            >
            <el-button type="danger" icon="el-icon-delete" @click="resetForm"
              >重置</el-button
            >
          </el-button-group>
        </ht-form-item>

        <ht-form-item
          label="选择报表"
          v-if="formData.type === 'addData' || formData.type === 'searchData'"
        >
          <ht-readonly-input v-model="formData.report.name" />
          <el-button-group style="margin-left:5px">
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="showReportDialog"
              >选择</el-button
            >
            <el-button type="danger" icon="el-icon-delete" @click="resetForm"
              >重置</el-button
            >
          </el-button-group>
        </ht-form-item>

        <ht-form-item
          label="反填字段"
          v-if="formData.type === 'addFlow' || formData.type === 'addData'"
        >
          <template>
            <el-table
              :data="formData.paramFields"
              max-height="250"
              border
              style="width: 100%"
            >
              <el-table-column
                prop="targetField"
                label="反填字段"
                align="center"
                min-width="230"
              >
                <template slot-scope="scope">
                  <ht-select
                    v-model="scope.row.targetField"
                    validate="required"
                    :options="targetFieldOptionList"
                  ></ht-select>
                </template>
              </el-table-column>
              <el-table-column
                prop="sourceField"
                label="取值字段"
                align="center"
                min-width="230"
              >
                <template slot-scope="scope">
                  <!--                   <ht-select
                    v-model="scope.row.sourceField"
                    validate="required"
                    :options="sourceFieldOptions"
                  ></ht-select> -->
                  <ht-select
                    value-key="name"
                    v-model="scope.row.sourceField"
                    validate="required"
                    :options="formVariables"
                  >
                    <template slot-scope="{options}">
                      <el-option-group
                        v-for="group in options"
                        :key="group.name"
                        :label="group.desc"
                      >
                        <el-option
                          v-for="item in group.fields"
                          :key="item.name"
                          :label="item.desc"
                          :value="item.name"
                        >
                          <span style="float: left">{{
                            item.desc + '(' + item.name + ')'
                          }}</span>
                        </el-option>
                      </el-option-group>
                    </template>
                  </ht-select>
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                align="right"
                class-name="default-row"
              >
                <template slot="header" slot-scope="scope">
                  <el-button
                    size="mini"
                    icon="el-icon-plus"
                    @click="handleAdd(scope.$index, scope.row)"
                    >增加</el-button
                  >
                </template>
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="danger"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.$index, scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </template>
        </ht-form-item>

        <ht-form-item
          label="打开方式"
          v-if="formData.type === 'addFlow' || formData.type === 'addData'"
        >
          <ht-radio v-model="formData.openType" :options="openTypeOptions" />
        </ht-form-item>

        <ht-form-item
          label="参数关系"
          v-if="formData.type === 'searchData' && formData.report.id"
        >
          <template>
            <el-table
              :data="formData.paramFields"
              max-height="250"
              border
              style="width: 100%"
            >
              <el-table-column
                prop="sourceField"
                :label="dataTemplateName"
                align="center"
                min-width="230"
              >
                <template slot-scope="scope">
                  <!--  <ht-select
                    v-model="scope.row.sourceField"
                    validate="required"
                    :options="sourceFieldOptions"
                  ></ht-select> -->
                  <ht-select
                    value-key="name"
                    v-model="scope.row.sourceField"
                    validate="required"
                    :options="formVariables"
                  >
                    <template slot-scope="{options}">
                      <el-option-group
                        v-for="group in options"
                        :key="group.name"
                        :label="group.desc"
                      >
                        <el-option
                          v-for="item in group.fields"
                          :key="item.name"
                          :label="item.desc"
                          :value="item.name"
                        >
                          <span style="float: left">{{
                            item.desc + '(' + item.name + ')'
                          }}</span>
                        </el-option>
                      </el-option-group>
                    </template>
                  </ht-select>
                </template>
              </el-table-column>
              <el-table-column
                prop="targetField"
                :label="formData.report.name"
                align="center"
                min-width="230"
              >
                <template slot-scope="scope">
                  <ht-select
                    v-model="scope.row.targetField"
                    validate="required"
                    :options="targetFieldOptionList"
                  ></ht-select>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="right">
                <template slot="header" slot-scope="scope">
                  <el-button
                    size="mini"
                    icon="el-icon-plus"
                    @click="handleAdd(scope.$index, scope.row)"
                    >增加</el-button
                  >
                </template>
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="danger"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.$index, scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </template>
        </ht-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose()" size="medium">取 消</el-button>
        <el-button type="primary" @click="saveData" size="medium"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <eip-flow-dialog
      ref="eipFlowDialog"
      @onConfirm="flowDialogOnConfirm"
      :single="true"
      append-to-body
    />

    <eip-data-template-dialog
      :appendToBody="true"
      ref="dataTemplateDialog"
      :single="true"
      @onConfirm="reportDialogOnConfirm"
    ></eip-data-template-dialog>
  </div>
</template>

<script>
import flow from '@/api/flow.js'
import req from '@/request.js'
import form from '@/api/form.js'
const eipFlowDialog = () => import('@/components/dialog/EipFlowDialog.vue')
const eipDataTemplateDialog = () =>
  import('@/components/dialog/EipDataTemplateDialog.vue')
import {mapState} from 'vuex'

export default {
  name: 'flow-form-add',
  props: ['defId', 'topDefKey'],
  components: {
    eipFlowDialog,
    eipDataTemplateDialog
  },
  data() {
    return {
      dialogVisible: false,
      dataTemplateName: '',
      formData: {
        type: '',
        flow: {
          id: '',
          name: '',
          key: ''
        },
        report: {
          id: '',
          name: '',
          key: ''
        },
        boDefKey: '',
        openType: 'old',
        paramFields: []
      },
      openTypeOptions: [
        {
          key: 'old',
          value: '当前页面打开'
        },
        {
          key: 'new',
          value: '新窗口打开'
        }
      ],
      targetFieldOptions: [],
      sourceFieldOptions: []
    }
  },
  computed: {
    ...mapState({
      formVariables(state) {
        return state.form.formListCommonVar.map(item => {
          return {
            ...item,
            fields: item.fields.map(it => {
              const fieldName = it.oldTableField
                ? `${it.tableName}${it.oldTableField}`
                : it.name
              return {
                ...it,
                name: it.oldTableField
                  ? fieldName.toLowerCase().replaceAll('_', '')
                  : fieldName
              }
            })
          }
        })
      }
    }),
    targetFieldOptionList() {
      let list =this.targetFieldOptions.filter(i => {
        return !['id_', 'ref_id_', 'form_data_rev_'].includes(i.key)
      })
        //新增数据需要增加外键反填设置
      if(this.formData.type ==='addData'){
        list.push({key:'updateRefId',value:'外键'})
      }
      return list
    }
  },
  methods: {
    //打开流程选择对话框
    showEipFlowDialog() {
      let params = []
      let names = []
      let ids = []
      if (this.formData.flow.name) {
        names = this.formData.flow.name.split(',')
        ids = this.formData.flow.id.split(',')
      }
      for (let i = 0; i < names.length; i++) {
        params.push({name: names[i], defKey: ids[i]})
      }
      this.$refs.eipFlowDialog.showDialog(params)
    },
    //选择流程后确认回调
    flowDialogOnConfirm(data) {
      //单选，只取第一条数据
      let d = data[0]
      this.formData.flow.name = d.name
      this.formData.flow.id = d.defId
      this.formData.flow.key = d.defKey

      //选择流程后查询目标流程关联的表单所需要反填的字段
      this.initFlowFormFieldOptions(this.formData.flow.key)

      //反射字段清空
      this.formData.paramFields = [{sourceField: '', targetField: ''}]
    },
    //打开报表选择对话框
    showReportDialog() {
      this.$refs.dataTemplateDialog.showDialog()
    },
    //选择报表后确认回调
    reportDialogOnConfirm(data) {
      //单选，只取第一条数据
      let d = data[0]

      this.formData.report.name = d.name
      this.formData.report.id = d.id
      this.formData.report.key = d.alias
      this.formData.boDefKey = d.boDefAlias

      this.updateTargetFieldOptions(d)
      //反射字段清空
      this.formData.paramFields = [{sourceField: '', targetField: ''}]
    },
    //获取已选择报表的表单数据-是否为外部表单
    updateTargetFieldOptions(dataTemplate) {
      var me_ = this
      this.$http
        .get(
          '${form}/bo/def/v1/getJsonByAlias?alias=' + dataTemplate.boDefAlias
        )
        .then(function(resp) {
          if (resp.data) {
            var boDef = resp.data
            me_.targetFieldOptions = []
            //选择报表后查询报表所对应表单的字段
            let formField = resp.data.ents[0].attributeList||[]
            var isExternal = boDef && boDef.boEnt.isExternal
            for (let i = 0; i < formField.length; i++) {
              let field = formField[i]
              if (!me_.existsOption(me_.targetFieldOptions, field.name)) {
                me_.targetFieldOptions.push({
                  key: isExternal ? field.oldTableField : field.name,
                  value: field.desc
                })
              }
            }
          }
        })
    },
    //打开对话框加载字段数据
    showDialog: function(param) {
      this.$validator = this.$root.$validator
      this.dialogVisible = true
      this.formData.type = param.type
      this.dataTemplateName = param.dataTemplateName || ''
      if (param.formData) {
        this.formData = JSON.parse(Base64.decode(param.formData))
        //加载反填的字段列表
        this.initTargetFieldOptions(this.formData)
      } else {
        this.resetForm()
      }

      //查询来源字段
      this.initSourceFieldOptions(param.defId)
    },
    initTargetFieldOptions(formData) {
      if (formData.type === 'addFlow') {
        //流程
        this.initFlowFormFieldOptions(formData.flow.key)
      } else {
        //查询数据
        this.initReportFormFieldOptions(formData.report.id)
      }
    },
    initReportFormFieldOptions(reportId) {
      if (!reportId) {
        return
      }
      req
        .get(
          window.context.form + '/form/dataTemplate/v1/getById?id=' + reportId
        )
        .then(response => {
          this.targetFieldOptions = []
          let d = response.data

          this.updateTargetFieldOptions(d)
        })
    },
    initFlowFormFieldOptions(flowKey) {
      if (!flowKey) {
        return
      }
      req
        .get(
          window.context.form +
            '/bo/def/v1/getBOTreeByFlowKey?flowKey=' +
            flowKey +
            '&topDefKey='
        )
        .then(response => {
          this.targetFieldOptions = []
          let data = response.data
          if (!this.formData.boDefKey) {
            this.formData.boDefKey = data.children[0].boDefAlias
          }
          let attributeList = data.children[0].children
          for (let i = 0; i < attributeList.length; i++) {
            let field = attributeList[i]
            if (!this.existsOption(this.targetFieldOptions, field.name)) {
              this.targetFieldOptions.push({
                key: field.name,
                value: field.comment
              })
            }
          }
        })
    },
    initSourceFieldOptions(defId) {
      req
        .get(window.context.form + '/bo/def/v1/getJson?id=' + defId)
        .then(response => {
          this.sourceFieldOptions = []
          let data = response.data
          var attributeList = data.boEnt.attributeList
          for (let i = 0; i < attributeList.length; i++) {
            let field = attributeList[i]
            if (!this.existsOption(this.sourceFieldOptions, field.name)) {
              this.sourceFieldOptions.push({
                key: field.name,
                value: field.comment
              })
            }
          }
        })
    },
    //判断下拉选项中是否含有某个字段
    existsOption(options, key) {
      return options.some(item => item.key === key)
    },
    //重置
    resetForm() {
      this.formData.flow = {id: '', name: '', key: ''}
      this.formData.report = {id: '', name: '', key: ''}
      this.formData.openType = 'old'
      this.formData.paramFields = []
    },
    //关闭对话框 重置数据
    handleClose() {
      this.dialogVisible = false
      this.formData.type = ''
      this.formData.flow = {id: '', name: '', key: ''}
      this.formData.report = {id: '', name: '', key: ''}
      this.formData.openType = 'old'
      this.formData.paramFields = []
    },
    //选择一行数据
    handleSelect(val, type, index, row) {
      //type: 1反填字段target 2取值字段source
      if (type === '1') {
        //反填字段变更
        row.targetField = val
      } else {
        row.sourceField = val
      }
    },
    //添加一行
    handleAdd(index, row) {
      let d = {
        sourceField: '',
        targetField: ''
      }
      this.formData.paramFields.push(d)
    },
    //删除一行
    handleDelete(index, row) {
      this.formData.paramFields.splice(index, 1)
    },
    saveData() {
      this.$validator.validateAll('flowFormAddObj').then(result => {
        if (result) {
          //确定动作
          this.dialogVisible = false
          this.$emit('saveFlowForm', this.formData)
        } else {
          this.$message.warning('请完善表单信息')
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
/deep/ .inputs.ht-form-inputs__inline {
  width: 280px;
  position: relative;
  div[aria-invalid='true'] {
    margin: 16px 0;
  }
  div[aria-invalid='true'] + .field-tail__wrap {
    text-align: left;
    position: absolute;
    top: calc(100% - 18px);
    left: 0;
    .el-form-item__error {
      top: calc(100% - 16px);
      position: static;
    }
  }
  div[aria-invalid='true'] + div + .field-tail__wrap {
    text-align: left;
    position: absolute;
    left: 15px;
    top: calc(100% - 18px);
    .el-form-item__error {
      top: calc(100% - 16px);
      position: static;
    }
  }
}
/deep/.default-row > .cell {
  overflow: visible !important;
}
/deep/.el-dialog {
  min-width: 1000px;
}
</style>
