<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="稽核名称">
              <j-input placeholder="请输入稽核名称" v-model="queryParam.tableName"></j-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="稽核描述">
              <j-input placeholder="请输入稽核描述" v-model="queryParam.tableTxt"></j-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 begin -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
<!--      <a-button @click="doCgformButton" type="primary" icon="highlight">自定义按钮</a-button>-->
<!--      <a-button @click="doEnhanceJs" type="primary" icon="strikethrough">JS增强</a-button>-->
<!--      <a-button @click="doEnhanceSql" type="primary" icon="filter">SQL增强</a-button>-->
<!--      <a-button @click="doEnhanceJava" type="primary" icon="tool">JAVA增强</a-button>-->
<!--      <a-button @click="importOnlineForm" type="primary" icon="database">导入数据库表</a-button>-->
      <a-button @click="goGenerateCode" type="primary" icon="database">代码生成</a-button>
      <!-- 高级查询区域 -->
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">批量操作<a-icon type="down" /></a-button>
      </a-dropdown>
    </div>
    <!-- 操作按钮区域 end -->

    <!-- table区域 begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        class="j-table-force-nowrap"
        @change="handleTableChange">

        <template v-slot:action="text, record">
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical"/>
          <a-dropdown>
            <a class="ant-dropdown-link">更多<a-icon type="down"/></a>
            <a-menu slot="overlay">
              <a-menu-item v-if="record.isDbSynch !== 'Y'">
                <a @click="openSyncModal(record.id)">同步数据库</a>
              </a-menu-item>
              <a-menu-item v-if="record.isDbSynch === 'Y' && record.tableType !== 3">
                <a @click="goPageOnline(record)">功能测试</a>
              </a-menu-item>
              <a-menu-item>
                <a @click="handleOnlineUrlShow(record)">配置地址</a>
              </a-menu-item>
<!--              <a-menu-item>-->
<!--                <a @click="goAuthConfig(record)">权限控制</a>-->
<!--              </a-menu-item>-->
<!--              <a-menu-item>-->
<!--                <a @click="doAuthConfig(record)">角色授权</a>-->
<!--              </a-menu-item>-->
<!--              <a-menu-item>-->
<!--                <a @click="copyConfig(record.id)">生成视图</a>-->
<!--              </a-menu-item>-->
<!--              <a-menu-item>-->
<!--                <a @click="showMyCopyInfo(record)">视图管理</a>-->
<!--              </a-menu-item>-->
<!--              <a-menu-item>-->
<!--                <a @click="handleDelete(record.id)">移除</a>-->
<!--              </a-menu-item>-->
            </a-menu>
          </a-dropdown>

        </template>
      </a-table>
    </div>
    <!-- table区域 end -->

    <!-- 任务添加 -->
    <form-head-modal ref="modalForm" @ok="modalFormOk"></form-head-modal>
    <code-generator ref="cg"></code-generator>
    <a-modal :style="{top:'5%',height:'95%'}"
             :width="500"
             :height="300"
             title="同步数据库"
             :visible="syncModalVisible"
             @cancel="handleCancleDbSync">
      <template v-slot:footer>
        <a-button @click="handleCancleDbSync">关闭</a-button>
        <a-button type="primary" :loading="syncLoading" @click="handleDbSync">确定</a-button>
      </template>

      <a-radio-group v-model="synMethod">
        <a-radio :style="{display:'block',width:'30px',height: '30px'}" value="normal">普通同步(保留表数据)</a-radio>
        <a-radio :style="{display:'block',width:'30px',height: '30px'}" value="force">强制同步(删除表,重新生成)</a-radio>
      </a-radio-group>

    </a-modal>

    <a-modal :title="onlineUrlTitle"
             :visible="onlineUrlVisible"
             @cancel="handleOnlineUrlClose">
      <template v-slot:footer>
        <a-button @click="handleOnlineUrlClose">关闭</a-button>
        <a-button type="primary" class="copy-this-text" :data-clipboard-text="onlineUrl" @click="onCopyUrl">复制</a-button>
      </template>
      <p>{{onlineUrl}}</p>
    </a-modal>

  </a-card>
</template>

<script>

import Clipboard from "clipboard";
import {JeecgListMixin} from '@/mixins/JeecgListMixin'
import FormHeadModal from './modules/FormHeadModal'
import CodeGenerator from './modules/CodeGenerator'
import {initDictOptions,filterDictText} from '@/components/dict/JDictSelectUtil'
import {getAction, postAction,deleteAction} from '@/api/manage'

export default {
  name: 'FormHeadList',
  mixins:[JeecgListMixin],
  inject:['closeCurrent'],
  components: {
    FormHeadModal,
    CodeGenerator,
  },
  data() {
    let self = this;
    return {
      description: '任务列表页面',
      columns2: [
        {
          title: '#',
          dataIndex: '',
          key:'rowIndex',
          width:60,
          align:"center",
          customRender:function (t,r,index) {
            return parseInt(index)+1;
          }
        },
        {
          title:'任务名称',
          align:"center",
          sorter: true,
          dataIndex: 'taskName',
          scopedSlots: { customRender: 'taskName' }
        },
        {
          title:'任务状态',
          align:"center",
          sorter: true,
          dataIndex: 'taskState_dictText'
        },
        {
          title:'任务开始时间',
          align:"center",
          sorter: true,
          dataIndex: 'taskStartTime'
        },
        {
          title:'任务结束时间',
          align:"center",
          sorter: true,
          dataIndex: 'taskEndTime'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align:"center",
          fixed:"right",
          width:147,
          scopedSlots: { customRender: 'action' }
        }
      ],
      columns : [{
        title : "#",
        dataIndex : "",
        key : "rowIndex",
        width : 60,
        align : "center",
        customRender(obj, name, x) {
          return parseInt(x) + 1;
        }
      }, {
        title : "表类型",
        align : "center",
        sorter : true,
        dataIndex : "tableType",
        customRender(obj, record) {
          let result = filterDictText(self.tableTypeDictOptions, obj);
          if (record.isTree === "Y") {
            result += "(树)"
          }
          if(record.themeTemplate === "innerTable") {
            result += "(内嵌)"
          }else if(record.themeTemplate === "erp") {
            result += "(ERP)"
          }else if(record.themeTemplate === "tab") {
            result += "(TAB)"
          }
          if(record.tableType === 3) {
            result += (record.relationType === 0 ? "(一对多)" : "(一对一)")
          }
          return result;
        }
      }, {
        title : "表名",
        sorter : true,
        align : "center",
        dataIndex : "tableName"
      }, {
        title : "表描述",
        align : "center",
        dataIndex : "tableTxt"
      }, {
        title : "版本",
        align : "center",
        dataIndex : "tableVersion"
      }, {
        title : "同步状态",
        align : "center",
        sorter : true,
        dataIndex : "isDbSynch",
        scopedSlots : {
          customRender : "dbsync"
        }
      }, {
        title : "创建时间",
        align : "center",
        sorter : true,
        dataIndex : "createTime"
      }, {
        title : "操作",
        dataIndex : "action",
        align : "center",
        scopedSlots : {
          customRender : "action"
        }
      }],
      url : {
        list : "/online/form/head/list",
        delete : "/online/form/head/delete",
        deleteBatch : "/online/form/head/deleteBatch",
        removeRecord : "/online/form/head/removeRecord",
        copyOnline : "/online/form/head/copyOnline",
        doDbSynch : "/online/form/api/doDbSynch/",
      },
      autoSearch: true,
      tableTypeDictOptions : [],
      sexDictOptions : [],
      syncModalVisible : false,
      syncFormId : "",
      synMethod : "normal",
      syncLoading : false,
      onlineUrlTitle : "",
      onlineUrlVisible : false,
      onlineUrl : "",
      selectedRowKeys : [],
      selectedRows : [],
      confirmVisible : false,
      selectTableType : 1
    }
  },
  created : function() {
    let self = this;
    initDictOptions("cgform_table_type").then(function(newItem) {
      if (newItem.success) {
        self.tableTypeDictOptions = newItem.result;
      }
    });
  },
  methods: {
    doDbSynch(length) {
      let self = this;
      postAction(this.url.doDbSynch + length, {
        synMethod : "1"
      }).then(function(data) {
        if (data.success) {
          self.$message.success(data.message);
          self.loadData();
        } else {
          self.$message.warning(data.message);
        }
      });
    },
    handleCancleDbSync : function() {
      this.syncModalVisible = false;
    },
    handleDbSync() {
      let self = this;
      this.syncLoading = true;
      postAction(this.url.doDbSynch + this.syncFormId + "/" + this.synMethod).then(function(data) {
        self.syncModalVisible = false;
        self.syncLoading = false;
        if (data.success) {
          self.$message.success(data.message);
          self.loadData();
        } else {
          self.$message.warning(data.message);
        }
      });
      setTimeout(function() {
        if (self.syncLoading) {
          self.syncModalVisible = false;
          self.syncLoading = false;
          self.$message.success("网络延迟,已自动刷新!");
          self.loadData();
        }
      }, 10000);
    },
    openSyncModal(syncFormId) {
      this.syncModalVisible = true;
      this.syncLoading = false;
      this.syncFormId = syncFormId;
    },
    goPageOnline(record) {
      if ("erp" === record.themeTemplate) {
        this.$router.push({
          path : "/online/cgformErpList/" + record.id
        });
      } else {
        if ("innerTable" === record.themeTemplate) {
          this.$router.push({
            path : "/online/cgformInnerTableList/" + record.id
          });
        } else {
          if ("tab" === record.themeTemplate) {
            this.$router.push({
              path : "/online/cgformTabList/" + record.id
            });
          } else {
            if ("Y" == record.isTree) {
              this.$router.push({
                path : "/online/cgformTreeList/" + record.id
              });
            } else {
              this.$router.push({
                path : "/online/cgformList/" + record.id
              });
            }
          }
        }
      }
    },
    handleOnlineUrlClose : function() {
      this.onlineUrlTitle = "";
      this.onlineUrlVisible = false;
    },
    handleOnlineUrlShow(record) {
      if ("erp" === record.themeTemplate) {
        this.onlineUrl = "/online/cgformErpList/".concat(record.id);
      } else {
        if ("innerTable" === record.themeTemplate) {
          this.onlineUrl = "/online/cgformInnerTableList/".concat(record.id);
        } else {
          if ("tab" === record.themeTemplate) {
            this.onlineUrl = "/online/cgformTabList/".concat(record.id);
          } else {
            if ("Y" === record.isTree) {
              this.onlineUrl = "/online/cgformTreeList/".concat(record.id);
            } else {
              this.onlineUrl = "/online/cgformList/".concat(record.id);
            }
          }
        }
      }
      this.onlineUrlVisible = true;
      this.onlineUrlTitle = "菜单链接[" + record.tableTxt + "]";
    },
    handleRemoveRecord(newWayId) {
      let self = this;
      this.$confirm({
        title : "确认要移除此记录?",
        onOk : function() {
          deleteAction(self.url.removeRecord, {
            id : newWayId
          }).then(function(data) {
            if (data.success) {
              self.$message.success("移除成功");
              self.loadData();
            } else {
              self.$message.warning(data.message);
            }
          });
        },
        onCancel : function() {
        }
      });
    },
    doEnhanceJs : function() {
      if (this.selectedRowKeys && this.selectedRowKeys.length === 1) {
        this.$refs.ehjs.show(this.selectedRows[0]);
      } else {
        this.$message.warning("请先选中一条记录");
      }
    },
    doEnhanceSql : function() {
      if (this.selectedRowKeys && this.selectedRowKeys.length === 1) {
        this.$refs.ehsql.show(this.selectedRows[0]);
      } else {
        this.$message.warning("请先选中一条记录");
      }
    },
    doEnhanceJava : function() {
      if (this.selectedRowKeys && this.selectedRowKeys.length === 1) {
        this.$refs.ehjava.show(this.selectedRowKeys[0]);
      } else {
        this.$message.warning("请先选中一条记录");
      }
    },
    doCgformButton : function() {
      if (this.selectedRowKeys && this.selectedRowKeys.length === 1) {
        this.$refs.btnList.show(this.selectedRowKeys[0]);
      } else {
        this.$message.warning("请先选中一条记录");
      }
    },
    importOnlineForm : function() {
      this.$refs.transd2o.show();
    },
    transOk : function() {
      this.loadData();
    },
    goGenerateCode() {
      if (this.selectedRowKeys && this.selectedRowKeys.length === 1) {
        let row = this.selectedRows[0];
        if (row) {
          if (row.isDbSynch && row.isDbSynch !== "N") {
            if (row.tableType !== 3) {
              this.$refs.cg.show(this.selectedRowKeys[0]);
            } else {
              this.$message.warning("请选中该表对应的主表生成代码");
            }
          } else {
            this.$message.warning("请先同步数据库!");
          }
        } else {
          this.$message.warning("请选择当前页数据!");
        }
      } else {
        this.$message.warning("请先选中一条记录");
      }
    },
    onSelectChange : function(index, isSelected) {
      this.selectedRowKeys = index;
      this.selectedRows = isSelected;
    },
    onCopyUrl : function() {
      let self = this;
      let clipboard = new Clipboard(".copy-this-text");
      clipboard.on("success", function() {
        clipboard.destroy();
        self.$message.success("复制成功");
        self.handleOnlineUrlClose();
      });
      clipboard.on("error", function() {
        self.$message.error("该浏览器不支持自动复制");
        clipboard.destroy();
      });
    },
    showMyCopyInfo(checkoutId) {
      this.$router.push({
        path : "/online/copyform/" + checkoutId
      });
    },
    copyConfig(obj) {
      let that = this;
      postAction("".concat(this.url.copyOnline, "?code=").concat(obj)).then(result => {
        if (result.success) {
          that.$message.success("复制成功");
          that.loadData();
        } else {
          that.$message.error("复制失败>>" + result.message);
        }
      });
    },
    batchDeleteCust() {
      if (this.url.deleteBatch) {
        if (this.selectedRowKeys.length <= 0) {
          this.$message.warning("请选择一条记录！");
        } else {
          this.confirmVisible = true;
        }
      } else {
        this.$message.error("请设置url.deleteBatch属性!");
      }
    },
    doBatchDelete(checked) {
      let self = this;
      let removed = "";
      let layer_i = 0;
      for (; layer_i < this.selectedRowKeys.length; layer_i++) {
        removed = removed + (this.selectedRowKeys[layer_i] + ",");
      }
      let channel_collection = this;
      this.loading = true;
      deleteAction(channel_collection.url.deleteBatch, {
        ids : removed,
        flag : checked
      }).then(function(data) {
        if (data.success) {
          self.$message.success(data.message);
          self.loadData();
          self.onClearSelected();
        } else {
          self.$message.warning(data.message);
        }
      }).finally(function() {
        self.loading = false;
        self.confirmVisible = false;
      });
    },
    goAuthConfig(record) {
      this.selectTableType = record.tableType;
      this.$refs.authManager.show(record.id);
    },
    doAuthConfig(record) {
      this.selectTableType = record.tableType;
      this.$refs.authSetter.show(record.id);
    }
  }
}

</script>

<style scoped>

</style>