<template>
  <div>
    <el-dialog
      :title="$t('label.select_url')"
      :visible.sync="nodeLinkVisiable"
      width="50%"
      :before-close="handleClose"
    >
      <div v-if="showLinkType" v-loading="loading">
        <div class="obpm-main mt-3">
          <div class="dialog-content">
            <el-form
              :inline="true"
              :model="linkInline"
              class="demo-form-inline"
            >
              <el-form-item :label="$t('label.name')">
                <el-input v-model="linkInline.name" size="mini"></el-input>
              </el-form-item>
              <el-form-item :label="$t('view.type')">
                <el-select v-model="linkInline.type" size="mini">
                  <el-option value=""></el-option>
                  <el-option :label="$t('view.form')" value="00"></el-option>
                  <el-option :label="$t('view.view')" value="01"></el-option>
                  <el-option :label="$t('label.url_in')" value="05"></el-option>
                  <el-option :label="$t('label.url_out')" value="06"></el-option>
                  <el-option :label="$t('label.email_url')" value="08"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="onSearch" size="mini">{{
                  $t('btns.query')
                }}</el-button>
                <el-button type="primary" @click="onReset" size="mini">{{
                  $t('btns.reset')
                }}</el-button>
              </el-form-item>
            </el-form>
            <el-table
              :data="nodeLinkData.datas"
              style="width: 100%"
              height="270px"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55"> </el-table-column>
              <el-table-column :label="$t('label.name')">
                <template slot-scope="scope">
                  <el-link
                    :style="{ color: '#66b1ff' }"
                    @click="handleClick(scope.row)"
                    >{{ scope.row.name }}</el-link
                  >
                </template>
              </el-table-column>
              <el-table-column :label="$t('view.type')">
                <template slot-scope="scope">
                  <el-link
                    :style="{ color: '#66b1ff' }"
                    @click="handleClick(scope.row)"
                    >{{ scope.row.typeName }}</el-link
                  >
                </template>
              </el-table-column>
              <el-table-column :label="$t('label.description')">
                <template slot-scope="scope">
                  <el-link
                    :style="{ color: '#66b1ff' }"
                    @click="handleClick(scope.row)"
                    >{{ scope.row.description }}</el-link
                  >
                </template>
              </el-table-column>
              <el-table-column prop="description" :label="$t('form.op')">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    @click="handleEdit(scope.$index, scope.row)"
                    >{{$t('form.edit')}}</el-button
                  >
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <el-pagination
              class="text-right pt-1"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="nodeLinkData.pageNo"
              :page-sizes="[10, 25, 50, 100]"
              :page-size="10"
              background
              layout="total, prev, pager, next, sizes"
              :total="nodeLinkData.rowCount"
            >
            </el-pagination>
          </div>
        </div>
        <div slot="footer" class="bar d-inline-block float-right">
          <el-button size="small" @click="handleClose">{{
            $t('btns.cancel')
          }}</el-button>
          <el-button
            type="danger"
            plain
            size="small"
            @click="clearSelectData"
            >{{ $t('btns.clean') }}</el-button
          >
          <el-button type="danger" size="small" plain @click="delSelectData">{{
            $t('btns.delete')
          }}</el-button>
          <el-button type="primary" size="small" @click="addNodeLink">{{
            $t('btns.new')
          }}</el-button>
        </div>
      </div>
      <div v-if="!showLinkType" v-loading="loading">
        <div class="obpm-main mt-3">
          <el-form
            :model="content"
            :rules="contentRules"
            ref="contentForm"
            label-position="left"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item :label="$t('label.name')" prop="name">
              <el-input v-model="content.name" size="mini"></el-input>
            </el-form-item>
            <el-form-item :label="$t('view.type')" prop="type">
              <el-select
                v-model="content.type"
                size="mini"
                style="width: 100%"
                @change="changeContentType"
              >
                <el-option :label="$t('view.form')" value="00"></el-option>
                <el-option :label="$t('view.view')" value="01"></el-option>
                <el-option :label="$t('label.url_in')" value="05"></el-option>
                <el-option :label="$t('label.url_out')" value="06"></el-option>
                <el-option :label="$t('label.email_url')" value="08"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('module.title')" prop="moduleid" v-if="showModule">
              <el-select
                v-model="content.moduleid"
                size="mini"
                style="width: 100%"
                @change="changeModules"
              >
                <el-option
                  v-for="item in allmodulesData"
                  :label="item.value"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              :label="$t('view.onactionform')"
              prop="actionForm"
              v-if="content.type === '00'"
            >
              <el-select
                v-model="content.actionForm"
                size="mini"
                style="width: 100%"
              >
                <el-option
                  v-for="item in moduleFormOptions"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              :label="$t('view.onactionview')"
              prop="actionView"
              v-if="content.type === '01'"
            >
              <el-select
                v-model="content.actionView"
                size="mini"
                style="width: 100%"
              >
                <el-option
                  v-for="item in moduleViewOptions"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              :label="$t('menu.customize_links_external')"
              prop="directory"
              v-if="content.type === '05' || content.type === '06'"
            >
              <el-select
                v-model="content.directory"
                size="mini"
                style="width: 50%"
                v-if="content.type === '05'"
              >
                <el-option label="portal/" value="portal"></el-option>
              </el-select>
              <el-input
                v-model="content.externalLinks"
                size="mini"
                style="width: 50%"
              ></el-input>
            </el-form-item>
            <el-form-item :label="$t('menu.paramete')" prop="tb">
              <template>
                <el-table :data="content.tb">
                  <el-table-column :label="$t('menu.parametername')">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.paramKey"
                        :placeholder="$t('placeholder.content')"
                        size="mini"
                      ></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column :label="$t('menu.parametervalue')">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.paramValue"
                        :placeholder="$t('placeholder.content')"
                        size="mini"
                      ></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column>
                    <template slot-scope="scope">
                      <el-button
                        size="small"
                        @click="delTbParamsSystem(scope.$index)"
                        type="danger"
                        >{{ $t('btns.delete') }}</el-button
                      >
                    </template>
                  </el-table-column>
                  <el-table-column :label="$t('view.op')">
                    <template slot="header">
                      <el-button size="small" @click="addTbParamsSystem">{{
                        $t('btns.add')
                      }}</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </template>
            </el-form-item>
            <el-form-item :label="$t('label.description')" prop="description">
              <el-input type="textarea" :rows="2" v-model="content.description">
              </el-input>
            </el-form-item>
          </el-form>
        </div>
        <div slot="footer" class="bar d-inline-block float-right">
          <el-button size="small" @click="logoutLinkType('contentForm')">{{
            $t('btns.exit')
          }}</el-button>
          <el-button type="primary" size="small" @click="saveLinkType">{{
            $t('btns.save')
          }}</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getModuleFormList } from '@/service/FormApi.js'
import {
  getModuleViewList,
  reqLinkDetail,
  reqLinkList,
  updateLinkDetail,
  delLinkList,
  addLinkDetail,
} from '@/service/ViewApi.js'
import { getAllmodules } from '@/service/CommonApi.js'
import { nameCheck } from '@/utils/utils.js'
import {delMsg} from '@/utils/elementui'
export default {
  data() {
    return {
      params: {
        appId: '',
        moduleId: '',
        searchword: '',
        type: '',
        viewId: '',
        pageNo: 1,
        linesPerPage: 10,
        name: '',
        description: '',
      },
      linkInline: {
        name: '', // 名称
        type: '', // 类型
      },
      content: {
        name: '', // 名称
        type: '00', // 类型
        moduleid: '', // 模块
        queryString: '', // 参数
        actionForm: '', // 作用表单
        actionView: '', // 作用视图
        directory: 'portal', // 自定义链接
        externalLinks: '', // 扩展链接
        tb: [
          // 参数
          {
            paramKey: '',
            paramValue: '',
          },
        ],
        description: '', // 描述
      },
      showLinkType: true,
      contentRules: {
        name: [
          { required: true, message: this.$t('placeholder.name'), trigger: 'blur' },
          { validator: nameCheck, trigger: 'blur' },
        ],
      },
      allmodulesData: [], // 模块的数据
      moduleFormOptions: [], //作用表单
      moduleViewOptions: [], // 作用视图
      delCheckBoxData: [], // checkbox选中的值
      isEdit: false, // 是否为编辑状态
      loading: true,
      nodeLinkData: {}, // 节点链接列表
      nodeLinkParams: {
        name: '',
        type: '',
        pageNo: 1,
        linesPerPage: 10,
      },
    }
  },
  methods: {
    // 弹框关闭回调
    handleClose() {
      this.isEdit = false
      this.onReset()
      this.logoutLinkType('contentForm')
      this.$emit('closeNodeLink')
    },
    // 表格查询
    onSearch() {
      this.nodeLinkParams = {
        ...this.nodeLinkParams,
        name: this.linkInline.name,
        type: this.linkInline.type
      }
      this.getNodeLinkList()
    },
    // 链接添加
    addNodeLink() {
      this.showLinkType = false
    },
    // 表格和表单重置重置
    onReset() {
      this.linkInline.name = ''
      this.linkInline.type = ''
      this.$emit('resetNodeLinkData')
    },
    // 链接编辑
    handleEdit(index, row) {
      this.getLinkDetail(row.id)
      this.isEdit = true
      let params = {
        ...this.params,
        appId: sessionStorage.getItem('appId'),
        moduleId: row.moduleid,
        searchword: '',
        viewId: '',
        pageNo: 1,
        linesPerPage: 100000,
        id: row.id,
      }
      this.params = params
      if (row.type == '00') {
        this.getListFrom(params)
      } else if (row.type == '01') {
        this.getListView(params)
      }
      this.showLinkType = false
    },
    // 选中表格前面的那个复选框
    handleSelectionChange(row) {
      this.delCheckBoxData = row
    },
    // 批量删除表格选中的数据
    async delSelectData() {
      let ids = []
      this.delCheckBoxData.map((item) => ids.push(item.id))
      if(this.delCheckBoxData.length > 0) {
        try{
          await delMsg(this.$t('msg.delConfirm'), this.$t('msg.tip'))
          const response = await delLinkList(ids)
          console.log(response,'response')
          if (response.data.errcode == 0) {
            this.$message.success(response.data.data)
            this.getNodeLinkList()
          }
        }catch(e){
          console.log(e)
        }
      }else {
        this.$message.error(this.$t('msg.check_data'))
      } 
    },
    // 清除【清空输入框的值】
    clearSelectData() {
      this.$parent.clearLinkName()
      this.handleClose()
    },
    /**
     * 切换分页，每页显示多少条
     */
    handleSizeChange(val) {
      this.nodeLinkParams.linesPerPage = val
      this.getNodeLinkList()
    },
    /**
     * 当前页
     */
    handleCurrentChange(val) {
      this.nodeLinkParams.pageNo = val
      this.getNodeLinkList()
    },
    // 点击表格字段
    handleClick(row) {
      this.$emit('selectNodeLinkValue', row)
      this.handleClose()
    },

    /**
     * 节点链接 查询
     */
    nodeLinkSearch(val) {
      this.nodeLinkParams.name = val.name
      this.nodeLinkParams.type = val.type
      this.getNodeLinkList()
    },

    /**
     * 节点链接 重置
     */
    resetNodeLinkData() {
      this.nodeLinkParams = {
        name: '',
        type: '',
        pageNo: 1,
        linesPerPage: 10,
      }
      this.getNodeLinkList()
    },
    // 表单保存
    saveLinkType() {
      let actionContent
      if (this.content.type == '00') {
        actionContent = this.content.actionForm
      } else if (this.content.type == '01') {
        actionContent = this.content.actionView
      } else if (this.content.type == '05' || this.content.type == '06') {
        actionContent = this.content.externalLinks
      }
      let params = {
        ...this.content,
        actionContent,
        queryString: JSON.stringify(this.content.tb),
        applicationid: sessionStorage.getItem('appId'),
        parentId: sessionStorage.getItem('appId'),
      }
      // 更新
      if (this.isEdit) {
        params.id = this.params.id
        updateLinkDetail(params, {
          onSucess: (response) => {
            if (response.data.errcode == 0) {
              this.$message.success(this.$t('msg.update_ss'))
              this.logoutLinkType('contentForm')
              this.$parent.resetNodeLinkData()
            }
          },
        })
      } else {
        // 新建
        addLinkDetail(sessionStorage.getItem('appId'), params, {
          onSucess: (response) => {
            if (response.data.errcode == 0) {
              this.$message.success(this.$t('msg.created_ss'))
              this.logoutLinkType('contentForm')
              this.$parent.resetNodeLinkData()
            }
          },
        })
      }
      setTimeout( () => {
        //保证保存成功即时刷新当前弹框界面
        this.getNodeLinkList()
      },200)
    },
    // 表单退出
    logoutLinkType(formName) {
      this.content = {
        name: '', // 名称
        type: '00', // 类型
        moduleid: '', // 模块
        actionForm: '', // 作用表单
        actionView: '', // 作用视图
        directory: 'portal', // 自定义链接
        externalLinks: '', // 扩展链接
        queryString: '', // 参数
        tb: [
          // 参数
          {
            paramKey: '',
            paramValue: '',
          },
        ],
        description: '', // 描述
      }
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields()
      }
      this.isEdit = false
      this.showLinkType = true
    },
    // 添加表单单行参数
    addTbParamsSystem() {
      this.content.tb.push({ paramKey: '', paramValue: '' })
    },
    // 删除表单单行参数
    delTbParamsSystem(index) {
      this.content.tb.splice(index, 1)
    },
    // 表单类型的改变
    changeContentType() {
      this.content.moduleid = ''
      ;(this.content.actionForm = ''), // 作用表单
        (this.content.actionView = '') // 作用视图
    },
    // 表单模块的改变
    changeModules() {
      this.moduleFormOptions = []
      this.moduleViewOptions = []
      let params = {
        ...this.params,
        appId: sessionStorage.getItem('appId'),
        moduleId: this.content.moduleid,
        name: '',
        description: '',
        viewId: '',
        pageNo: 1,
        linesPerPage: 100000,
      }
      // 清空作用表单视图的值
      this.content.actionForm = ''
      this.content.actionView = ''
      this.content.externalLinks = ''
      if (this.content.type == '00') {
        this.getListFrom(params)
      } else if (this.content.type == '01') {
        this.getListView(params)
      }
    },
    /**
     * 获取作用表单
     */
    getListFrom(params) {
      this.loading = true
      getModuleFormList(params, {
        onSucess: (response) => {
          this.loading = false
          if (response.data.errcode == 0) {
            let data = response.data.data.datas
            let dataArr = []
            for (let i = 0; i < data.length; i++) {
              if (data[i].type == 1) {
                dataArr.push(data[i])
              }
            }
            this.moduleFormOptions = dataArr
          }
        },
      })
    },
    /**
     * 获取作用视图
     */
    getListView(params) {
      this.loading = true
      getModuleViewList(params, {
        onSucess: (response) => {
          this.loading = false
          if (response.data.errcode == 0) {
            this.moduleViewOptions = response.data.data.datas
          }
        },
      })
    },

    /**
     * 获取链接详情列表
     */
    getLinkDetail(linkId) {
      this.loading = true
      reqLinkDetail(linkId, {
        onSucess: (response) => {
          if (response.data.errcode == 0) {
            this.loading = false
            let data = response.data.data
            // console.log(data)
            this.content = {
              name: data.name, // 名称
              type: data.type, // 类型
              moduleid: data.moduleid, // 模块
              queryString: data.queryString, // 参数
              actionForm: data.type == '00' ? data.actionContent : '', // 作用表单
              actionView: data.type == '01' ? data.actionContent : '', // 作用视图
              directory: data.directory, // 自定义链接
              externalLinks:
                data.type == '05' || data.type == '06'
                  ? data.actionContent
                  : '', // 扩展链接
              tb: data.queryString ? eval(data.queryString) : [],
              description: data.description, // 描述
            }
          }
        },
      })
    },
    /**
     * 获取所有模块
     */
    /**
     * 获取菜单树形结构所有模块列表
     */
    async getAllmodules() {
      let appId = sessionStorage.getItem('appId')
      let currentModuleId = ''
      this.loading = true
      let response = await getAllmodules(appId, currentModuleId)
      if (response.data.errcode == 0) {
        this.loading = false
        this.allmodulesData = response.data.data
      }
    },
    /**
     * 获取节点链接的数据
     */
    getNodeLinkList() {
      let params = {
        ...this.nodeLinkParams,
        appId: sessionStorage.getItem('appId'),
      }
      reqLinkList(params, {
        onSucess: (response) => {
          if (response.data.errcode == 0) {
            let data = response.data.data.datas
            for (let i = 0; i < data.length; i++) {
              if (data[i].type == '00') {
                data[i].typeName = this.$t('view.form')
              } else if (data[i].type == '01') {
                data[i].typeName = this.$t('view.view')
              } else if (data[i].type == '05') {
                data[i].typeName = this.$t('label.url_in')
              } else if (data[i].type == '06') {
                data[i].typeName = this.$t('label.url_out')
              } else if (data[i].type == '08') {
                data[i].typeName = this.$t('label.email_url')
              }
            }
            this.nodeLinkData = response.data.data
          }
        },
      })
    },
  },
  created() {
    this.getAllmodules()
    this.getNodeLinkList()
  },
  props: {
    nodeLinkVisiable: {
      type: Boolean,
    },
  },
  computed: {
    showModule() {
      return this.content.type != '05' && this.content.type != '06'
    },
  },
}
</script>
<style scoped>
.dialog-content {
  overflow: hidden;
}
</style>
