<template>
  <div>
    <el-row>
      <el-col :span="4">
        <!-- 头部工具栏 -->
        <el-button @click="addCrawlRule()" style="margin-left:20px;" type="success" size="mini"><i
            class="el-icon-plus"></i> 新增
        </el-button>
        <el-button type="primary" style="margin-left:20px;" size="mini" @click="handleExport"><i
            class="el-icon-download"></i> 导出
        </el-button>
        <el-button type="warning" style="margin-left:20px;" size="mini" @click="handleImport"><i
            class="el-icon-upload2"></i> 导入
        </el-button>
        <input
            type="file"
            ref="fileInput"
            style="display: none"
            accept=".json"
            @change="handleFileChange"
        />
      </el-col>
      <el-col :span="20">
        <div style="text-align: right;">
          <el-input style="width:150px;" size="mini" v-model="querySiteName" placeholder="站点名称">
          </el-input>
          <el-cascader
              v-model="queryNation"
              :options="nationOptions"
              placeholder="所在国家/地区"
              style="width:150px;margin-left:20px"
              size="mini"
              :show-all-levels="false"
              :clearable="true"></el-cascader>
          <el-cascader
              v-model="queryCarrierType"
              :options="carrierTypeOptions"
              placeholder="载体类型"
              style="width:150px;margin-left:20px"
              size="mini"
              :show-all-levels="false"
              :clearable="true"></el-cascader>
          <el-cascader
              v-model="querySiteType"
              :options="siteTypeOptions"
              placeholder="站点类型"
              style="width:150px;margin-left:20px"
              size="mini"
              :show-all-levels="false"
              :clearable="true"></el-cascader>
          <el-cascader
              v-model="queryResourceType"
              :options="resourceTypeOptions"
              placeholder="资源类型"
              style="width:150px;margin-left:20px"
              size="mini"
              :show-all-levels="false"
              :clearable="true"></el-cascader>
          <el-cascader
              v-model="queryDelFlag"
              :options="statusOptions"
              placeholder="启用状态"
              style="width:150px;margin-left:20px"
              size="mini"
              :show-all-levels="false"
              :clearable="true"></el-cascader>
          <el-button @click="query" type="primary" size="mini" style="margin-left:20px;"><i
              class="el-icon-search"></i> 查询
          </el-button>
          <el-button @click="resetSearch" type="info" size="mini" style="margin-left:20px;"><i
              class="el-icon-refresh"></i> 重置
          </el-button>
        </div>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <!-- 内容展示部分 -->
        <targetTable :metaData="metadata" :tableData="tableData" :isLoading="isLoading" labelName="状态"
                     @selection-change="handleSelectionChange">
          <!--          <template #status="{index,tagStu}">-->
          <!--            <el-tag type="danger" v-if="tagStu.status===2">已停止</el-tag>-->
          <!--            <el-tag type="warning" v-if="tagStu.status===1">已暂停</el-tag>-->
          <!--            <el-tag type="success" v-if="tagStu.status===0">已启用</el-tag>-->
          <!--          </template>-->
          <template #default="{ index,handscope }">
            <el-tooltip v-if="handscope.row.status === 0" class="item" effect="dark"
                        content="取消采集"
                        placement="top">
              <el-button type="danger" icon="el-icon-switch-button" @click="enable(index,2,handscope)" size="mini"
                         plain circle></el-button>
            </el-tooltip>
            <el-tooltip v-if="handscope.row.status === 0" class="item" effect="dark"
                        content="暂停采集"
                        placement="top">
              <el-button type="warning" icon="el-icon-video-pause" @click="enable(index,1,handscope)" size="mini"
                         plain circle></el-button>
            </el-tooltip>
            <el-tooltip v-if="handscope.row.status !== 0" class="item" effect="dark"
                        content="启用采集"
                        placement="top">
              <el-button type="success" icon="el-icon-caret-right" @click="enable(index,0,handscope)" size="mini"
                         plain circle></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="编辑/查看" placement="top">
              <el-button type="primary" icon="el-icon-edit" @click="viewDetail(index, tableData, handscope)"
                         size="mini"
                         plain circle></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark"
                        content="运行单站点任务"
                        placement="top">
              <el-button type="success" icon="el-icon-s-promotion" @click="runSingleTask(handscope)" size="mini"
                         plain circle></el-button>
            </el-tooltip>
            <el-button type="danger" size="mini" icon="el-icon-delete" plain circle
                       @click="deleteCrawlRuleChild(index, tableData, handscope)"></el-button>
          </template>
        </targetTable>
        <el-pagination background layout="total, prev, pager, next, jumper" :total="total"
                       @current-change="onPageChange" style="padding: 15px" :current-page="pageIndex"
        ></el-pagination>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import Vue from 'vue'
import {
  Button,
  ButtonGroup,
  Cascader,
  Col,
  Dialog,
  Divider,
  Dropdown,
  DropdownItem,
  DropdownMenu,
  Form,
  FormItem,
  Input,
  Message, MessageBox,
  Option,
  RadioGroup,
  Row,
  Select,
  TabPane,
  Tabs,
  Tag,
  Tooltip
} from 'element-ui'
import targetWebsiteApi from '../../js/api/targetWebsiteApi'
import targetTable from './TargetTable.vue'
import metaDictApi from '../../js/api/metaDictApi'
import 'font-awesome/css/font-awesome.css'
import taskApi from "@/js/api/taskApi";

Vue.use(Select)
Vue.use(Option)
Vue.use(Input)
Vue.use(Row)
Vue.use(Col)
Vue.use(Button)
Vue.use(Dialog)
Vue.use(Form)
Vue.use(FormItem)
Vue.use(Divider)
Vue.use(Cascader)
Vue.use(Dropdown)
Vue.use(DropdownMenu)
Vue.use(DropdownItem)
Vue.use(Tabs)
Vue.use(TabPane)
Vue.use(RadioGroup)
Vue.use(Tag)
Vue.use(ButtonGroup)
Vue.use(Tooltip)

export default {
  name: 'WebsiteManage',
  inject: ['reload'],
  components: {
    'targetTable': targetTable
  },
  data() {
    return {
      isLoading: false,
      queryRedisDailyCount: false,
      showCronList: true,
      showDepthList: true,
      dialogVisible: false,
      formLabelWidth: '100px',
      formData: {},
      tableData: [],
      total: 0,
      multipleSelection: [],
      resourceTypeOptions: [],
      siteTypeOptions: [],
      carrierTypeOptions: [],
      nationOptions: [],
      querySiteName: '',
      queryCarrierType: '',
      querySiteType: '',
      queryResourceType: '',
      queryNation: '',
      queryDelFlag: '',
      statusOptions: [
        {
          value: "0",
          label: "已启用"
        },
        {
          value: "1",
          label: "暂停"
        },
        {
          value: "2",
          label: "停止"
        },

      ],
      sortFlag: null,
      sortMethod: null,
      pageIndex: 1,
      pageSize: 10
    }
  },
  computed: {
    metadata: function () {
      let temp = [];
      this.$store.state.metadata.metadata.forEach(element => {
        if (element.tableName === 'target_website') {
          let tempElement = {...element};
          tempElement.minWidth = tempElement.columnWidth + "%";
          tempElement.columnWidth = 0;
          temp.push(tempElement);
        }
      });
      return temp;
    },
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    viewDetail(index, tableData, handscope) {
      this.showCronList = true;
      this.showDepthList = true;
      // this.formData = {...tableData[Number(index)]};
      this.formData = handscope.row;
      let editParam = {};
      editParam.data = this.formData;
      editParam.isEdit = true;
      this.$router.push({path: '/oscm/target/website/settings', query: editParam});
    },
    addCrawlRule() {
      this.$router.push({path: '/oscm/target/website/settings'})
    },
    deleteCrawlRuleChild(index, tableData, handscope) {
      MessageBox.confirm("是否删除？", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      })
          .then(() => {
            this.formData = handscope.row;
            console.log(this.formData.id);
            targetWebsiteApi.delete({id: this.formData.id}, (response) => {
              if (response.data.code === 200) {
                Message({
                  message: "删除成功",
                  type: "success",
                });
              }
              this.queryAllPageable(this.pageIndex - 1, this.pageSize);
            })
          })
          .catch(() => {
          })
    },
    addFieldRule() {
      this.formData.rules.push({value: '', key: Date.now(), field: '', show: true})
    },
    setQueryParams() {
      let queryParams = {};
      if (this.querySiteName.length > 0) {
        queryParams.siteName = this.querySiteName;
      }
      if (this.queryDelFlag.length > 0) {
        queryParams.status = this.queryDelFlag[0];
      }
      if (this.queryNation.length > 0) {
        queryParams.region = this.queryNation[0];
      }
      if (this.queryCarrierType.length > 0) {
        queryParams.carrierType = this.queryCarrierType[0];
      }
      if (this.querySiteType.length > 0) {
        queryParams.siteType = this.querySiteType[0];
      }
      if (this.queryResourceType.length > 0) {
        queryParams.resourceType = this.queryResourceType[0];
      }
      return queryParams;
    },
    queryAllPageable(index, size) {
      this.isLoading = true;
      let queryParams = this.setQueryParams();
      targetWebsiteApi.queryCommon(queryParams, index, size, (response) => {
        if (response.data.code === 200) {

          this.tableData = response.data.content;
          let ids = ""
          for (let j = 0; j < this.tableData.length; j++) {
            ids = ids + this.tableData[j].id + ","
          }
          this.total = parseInt(response.data.message);
          this.isLoading = false;
        } else {
          Message({
            message: '查询失败',
            type: 'error'
          });
          this.isLoading = false;
        }
      })
    },
    onPageChange(index) {
      this.pageIndex = index
      this.queryAllPageable(index - 1, this.pageSize);
    },
    buildDictTree(data, columnString) {
      let siteOptions = []
      let nodeList = []
      data.forEach(e => {
        if (e.columnName === columnString)

          nodeList.push({
            value: e.dictCode,
            label: e.dictValue,
            children: undefined,
            parentDictCode: e.parentDictCode
          });
      })
      nodeList.forEach(e1 => {
        if (e1.parentDictCode !== undefined) {
          nodeList.forEach(e2 => {
            if (e1.parentDictCode === e2.value) {
              if (e2.children === undefined) {
                e2.children = []
              }
              e2.children.push(e1);
            }
          })
        } else {
          siteOptions.push(e1);
        }
      })
      return siteOptions;
    },
    resetSearch() {
      this.pageIndex = 0
      this.querySiteName = ''
      this.queryCarrierType = ''
      this.querySiteType = ''
      this.queryResourceType = ''
      this.queryNation = ''
      this.queryDelFlag = ''
      this.queryAllPageable(0, this.pageSize);
    },
    query() {
      this.pageIndex = 0
      this.queryAllPageable(0, this.pageSize);
    },
    enable(index, status, column) {
      column.row.status = status;
      targetWebsiteApi.update(column.row, (response) => {
        console.log(response);
        if (response.data.code === 200) {
          this.dialogVisible = false;
          Message({
            message: '操作成功',
            type: 'success'
          });
          this.queryAllPageable(this.pageIndex - 1, this.pageSize);
        } else {
          Message({
            message: response.data.message,
            type: 'error'
          });
        }
      })
    },
    runSingleTask(handscope) {
      const row = handscope.row;
      const websiteId = parseInt(row.id)
      taskApi.runSingleTasks([websiteId], (response) => {
        if (response.data.code === 200) {
          Message({
            message: "启动" + row.siteName + '的单站点采集任务',
            type: "success",
          });
        }
      });
    },
    cronChange(val) {
      if (val === '-1') {
        this.showCronList = false;
        this.formData.cron = '';
      }
    },
    depthChange(val) {
      if (val === '-1') {
        this.showDepthList = false;
        this.formData.depth = '';
      }
    },
    async handleExport() {
      try {
        // 发送GET请求到导出接口
        await targetWebsiteApi.export((response) => {
          // 创建下载链接
          const url = window.URL.createObjectURL(new Blob([response.data]))
          const link = document.createElement('a')
          link.href = url
          link.setAttribute('download', 'target_websites.json') // 设置下载文件名
          document.body.appendChild(link)
          link.click()
          // 清理
          document.body.removeChild(link)
          window.URL.revokeObjectURL(url)
          Message.success('导出成功')
        })

      } catch (error) {
        console.error('导出失败:', error)
        Message.error('导出失败: ' + (error.response?.data?.message || error.message))
      }
    },

    // 触发文件选择对话框
    handleImport() {
      this.$refs.fileInput.click()
    },

    // 处理文件选择
    async handleFileChange(event) {
      const file = event.target.files[0]
      if (!file) return

      // 验证文件类型
      if (!file.name.endsWith('.json')) {
        Message.error('请选择JSON文件')
        return
      }

      try {
        // 创建FormData对象
        const formData = new FormData()
        formData.append('file', file)

        // 发送POST请求到导入接口
        await targetWebsiteApi.import(formData, (response) => {
          Message.success(response.data)
          // 清空文件输入，以便可以重复选择同一文件
          event.target.value = ''
          // 可选：导入成功后刷新数据
          this.resetSearch()
        })

      } catch (error) {
        console.error('导入失败:', error)
        Message.error('导入失败: ' + (error.response?.data?.message || error.message))
      }
    }
  },
  mounted: function () {
    this.queryAllPageable(0, this.pageSize);
    if (this.nationOptions.length === 0) {
      metaDictApi.queryByTableName('target_website', (response) => {
        if (response.data.code === 200) {
          this.nationOptions = this.buildDictTree(response.data.content, 'region');
          this.resourceTypeOptions = this.buildDictTree(response.data.content, 'resourceType');
          this.siteTypeOptions = this.buildDictTree(response.data.content, 'siteType');
          this.carrierTypeOptions = this.buildDictTree(response.data.content, 'carrierType');
        }
      })
    }
  }
}
</script>

<style scoped>
.searchBar {
  padding-bottom: 20px;
  border-bottom: solid 1px lightgrey;
}

.dialogForm {
  display: flex;
  justify-content: center;
}

.demo-form {
  width: 450px;
}

.demo-form .el-input, .el-cascader {
  width: 300px;
}

.dialogForm, .el-pagination {
  display: flex;
  justify-content: center;
}

.el-divider {
  margin: 0 !important;
  font-size: 20px;
}

.fa {
  margin: 0 3px 0 3px;
  font-size: 16px;
  color: #606266;
  cursor: pointer;
}
</style>