<template>
  <div class="bodyBoxs">
    <div class="boxs">
      <div class="topBox" style="display: flex;justify-content: flex-end;">
        <!-- <div style="margin-bottom: 15px;width: 700px;float: left">
          <el-input v-model="search" placeholder="请输入奖品名称" class="input-with-select">
            <el-button slot="append" style="width: 70px;" icon="el-icon-search" @click="getData(1)" />
            <el-button slot="append" style="border-left: rgb(220,223,230) solid 1px" icon="el-icon-download"
              @click="userExport"></el-button>
          </el-input>

        </div> -->
        <el-button style="height: 36px;margin-right: 20px;" type="success" @click="handleAdd">新增任务</el-button>
      </div>


      <el-table v-loading="loading" ref="multipleTable" :data="tableData" style="width: 100%">
        <el-table-column label="任务ID" prop="id">
        </el-table-column>
        <el-table-column label="任务名称" prop="task_name">
        </el-table-column>

        <el-table-column prop="task_type" label="任务类型" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.task_type == 1 ? '每天' : scope.row.task_type == 2 ? '每周' : scope.row.task_type == 3 ? '每月' : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="keyword" label="关键词" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="task_value" label="任务值" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="state" label="启用状态">
          <template #default="{ row }">
            <el-tag :type="row.state ? 'success' : 'info'" effect="dark">
              {{ row.state ? '已启用' : '未启用' }}
            </el-tag>
          </template>
          <!-- <template #default="{ row }">
            <el-switch v-model="row.state" @change="updateState(row)">
              <span slot="icon" class="el-switch--disabled-text" v-if="!row.state"></span>
            </el-switch>
          </template> -->
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="text" @click="handleEdit(row)">编辑</el-button>
            <el-button type="text" @click=" delTask(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>


      <el-pagination :current-page="currentPage" :page-sizes="[10, 20, 30, 50]" :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>

    <!-- 新增/编辑弹框 -->
    <el-dialog :title="boxTitle" :visible.sync="dialogVisible" :before-close="handleClose">
      <el-form :rules="rules" ref="ruleForm" :model="dataForm" label-width="120px"  label-position="right"
        @keyup.enter.native="handleDialogOk">
        <el-form-item label="任务名称" prop="">
          <!-- <el-input v-model="taskName" maxlength="18" oninput="value=value.replace(/^([0-9-]\d*\.?\d{0,3})?.*$/,'$1')"
            placeholder="请输入任务名称"></el-input> -->
          <el-input v-model="taskName" maxlength="18" oninput="" placeholder="请输入任务名称"></el-input>
        </el-form-item>

          <!-- <el-form-item label="任务名称" prop="">
            <el-select v-model="modelId" placeholder="请选择">
            <el-option
                v-for="item in selectData"
                :key="item.id"
                :value="item.id">{{item.name}}
              </el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item
            v-for="(domain, index) in dynamicValidateForm.domains"
            :label="'关键词' + index"
            :key="domain.key"
            :prop="'domains.' + index + '.value'"
            :rules="{
              required: true, message: '域名不能为空', trigger: 'blur'
            }"
          >
          <el-input v-model="domain.value" style="width:80%"></el-input>
          <i class="el-icon-plus" style="margin-left:10px;" v-if="index == 0" @click="addDomain"></i>
          <i class="el-icon-minus" style="margin-left:10px" v-if="index > 0" @click.prevent="removeDomain(domain)"></i>
  </el-form-item>
        <!-- <el-form-item label="关键词" prop="">
          <el-input style="min-width: 300px;" v-model="keyword" maxlength="18" oninput=""
            placeholder="请输入关键词(多个关键词用英文逗号分割)"></el-input>
        </el-form-item> -->
        <el-form-item label="任务类型" prop="">
          <el-select v-model="taskType" placeholder="请选择">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="任务值" prop="">
          <!-- <el-input v-model="taskValue" maxlength="18" oninput="value=value.replace(/[^\d]/g, '')"></el-input> -->
          <el-input v-model="taskValue" maxlength="18" oninput="" placeholder="请输入任务值(数字)"></el-input>
          <el-tag type="danger">注意：任务值是指：比如选择每天值是 1 那么代表每天执行一次</el-tag><br/>
          <el-tag type="danger">如果每周值是 2 就是每两周执行一次。如果需要一天多个文章可以创建多个任务</el-tag>
        </el-form-item>
        <br />
        <el-form-item label="是否启用" prop="">
          <el-switch v-model="taskForbid" @change="handleSwitchChange2(taskForbid)">
          </el-switch>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleDialogOk(curId == -1 ? 0 : 1)">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getToken } from '@/utils/auth'
// import { addTask } from '@/api/api'


export default {
  data() {
    return {
      dynamicValidateForm: {
          domains: [{
            value: ''
          }],
          email: ''
        },
      selectData:[],
      dataForm: {},
      dialogVisible: false,
      rules: {
        regionId: [
          { required: true, message: '景区不能为空', trigger: 'blur' }
        ],
        low: [
          { required: true, message: '优惠价不能为空', trigger: 'blur' }
        ],
        volume: [
          { required: true, message: '人流量不能为空', trigger: 'blur' }
        ]
      },
      regionList: [],
      options: [{
        value: 1,
        label: '每天'
      }, {
        value: 2,
        label: '每周'
      }, {
        value: 3,
        label: '每月'
      }],
      taskType: '',
      taskValue: '',
      taskName: '',
      keyword: '',
      modelId:1,

      pageSize:15,

      isExchange: '2',
      isAward: '2',
      tableData: [],
      loading: false,
      awardId: '',
      pages: 1,
      page: 1,
      isAddr: '2',
      size: 10,
      total: 0,
      currentPage: 1,
      search: '',
      boxTitle: '',
      taskForbid: false,
      // taskForbid1: false,

      curId: -1
    }
  },
  async created() {
    this.getData(3)
    this.getSelect()
  },
  methods: {
    submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            alert('submit!');
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      removeDomain(item) {
        var index = this.dynamicValidateForm.domains.indexOf(item)
        if (index !== -1) {
          this.dynamicValidateForm.domains.splice(index, 1)
        }
      },
      addDomain() {
        this.dynamicValidateForm.domains.push({
          value: '',
          key: Date.now()
        });
      },
    getSelect(){
      console.log('执行了')
      this.$api.getSelectModel({}).then((res) => {
        console.log('-__________>'.res)
          this.selectData = res.data
      }).catch((res) => {
        this.loading = false;
      });
    },
    divPage(page = this.page) {
      // this.page++

      this.$api.getTaskList({
        page,
        size: this.pageSize,
        // search: this.search,
      }).then((res) => {
        this.loading = false;
        console.log('任务列表返回值22222222222222：', res);
        // this.tableData = res.data.data;
        if (res.code == 0) {
          this.tableData = res.data.data;

          // this.total = res.data.total;
        } else {
          this.$message.error(res.message)
        }
      }).catch((res) => {
        this.loading = false;
      });
    },

    updateState(row) {

      console.log('wai--row', row);
      let parms = {
        id: row.id,
        state: row.state
      }
      // return console.log('wai--parms', {
      //   id: row.id,
      //   state: row.state
      // });

      this.$api.updateTask(parms).then((res) => {
        this.loading = false;
        console.log('更新任务状态返回值：', res);
        // this.tableData = res.data.data;
        if (res.code == 0) {
          this.dialogVisible = false;
          this.getData(3)
          this.$message({
            message: '修改任务状态成功',
            type: 'success'
          });
        } else {
          this.$message.error(res.message)
        }
      }).catch((res) => {
        this.loading = false;
      });
    },

    delTask(id) {
      // delTask
      this.$api.delTask({ id }).then((res) => {
        this.loading = false;
        console.log('删除任务返回值：', res);
        // this.tableData = res.data.data;
        if (res.code == 0) {
          this.dialogVisible = false;
          this.getData(2)

        } else {
          this.$message.error(res.message)
        }
      }).catch((res) => {
        this.loading = false;
      });
    },
    handleSwitchChange2(e) {
      console.log('handleSwitchChange2', e);

      // this.taskForbid = !this.taskForbid
    },
    handleEdit(row) {
      console.log('row---edit', row);
      let keywordArray = row.keyword.split(',');
// 将数组赋给 this.dynamicValidateForm.domains 中的 value 属性
    this.dynamicValidateForm.domains = keywordArray.map(keyword => {
      return { value: keyword.trim() }; // 使用 trim() 来去除可能的空格
    });
      this.dialogVisible = true;
      this.dataForm = {}
      this.curId = row.id
      this.modelId = row.model_id
      this.taskName = row.task_name
      this.keyword = row.keyword
      this.taskValue = row.task_value
      this.taskType = row.task_type
      this.taskForbid = row.state ? true : false
      this.boxTitle = '编辑任务'
    },
    handleDelete(row) {
      console.log('row---del', row);

    },
    handleSwitchChange(row) {
      console.log('row---', row);
    },
    getData(type) {

      console.log('type----', type);
      this.loading = true;
      this.$api.getTaskList({
        page: this.page,
        size: this.pageSize,
        search: this.search,
      }).then((res) => {
        this.loading = false;
        console.log('任务列表返回值：', res);
        // this.tableData = res.data.data;
        if (res.code == 0) {
          this.tableData = res.data.data.reverse();

          this.total = res.data.total;
          // this.page = 1
          // this.currentPage = 1

          if (type == 0) {
            this.$message({
              message: '新增任务成功',
              type: 'success'
            });
          } else if (type == 1) {
            this.$message({
              message: '修改任务成功',
              type: 'success'
            });
          } else if (type == 2) {
            this.$message({
              message: '删除任务成功',
              type: 'success'
            });
          }
        } else {
          this.$message.error(res.message)
        }
      }).catch((res) => {
        this.loading = false;
      });
    },

    // 打开新增数据弹窗
    handleAdd() {
      this.dialogVisible = true;
      this.dataForm = {}
      this.boxTitle = '新增任务'
      this.dynamicValidateForm.domains = [{
            value: ''
          }]
      this.curId = -1

      this.taskName = ''
      this.keyword = ''
      this.taskValue = ''
      this.taskType = ''

      this.taskForbid = false

    },
    // 打开编辑弹窗
    handleClick(val) {
      this.dialogVisible = true;
      this.dataForm = { ...val };// 对表单进行重置，即修改表单的数据不想保存，关闭弹框，数据不会跟着变。

    },
    // 编辑确定按钮
    handleDialogOk(type) {
      // this.$refs['ruleForm'].validate(async (valid) => {
      //   if (valid) {
      //     const res = await saveDataAPI(this.dataForm)
      //     this.$message({ type: 'success', message: res.msg })
      //     this.dialogVisible = false
      //   }
      // });

      let parms = {}
      if (type == 0) {
        parms = {
          task_name: this.taskName,
          keyword: this.keyword,
          task_type: this.taskType,
          task_value: this.taskValue,
          model_id: this.modelId,
          state: this.taskForbid ? 1 : 0
        }
      } else {
        parms = {
          id: this.curId,
          task_name: this.taskName,
          keyword: this.keyword,
          task_type: this.taskType,
          task_value: this.taskValue,
          model_id: this.modelId,
          state: this.taskForbid ? 1 : 0

        }
      }
      parms.keyword = this.dynamicValidateForm.domains
      console.log('参数-----------', parms);


      if (!this.taskName) {
        return this.$message.error('请输入任务名称');
      } else if (!parms.keyword[0].value) {

        return this.$message.error('请输入关键词');

      }
      else if (!this.taskType) {
        return this.$message.error('请选择任务类型');

      } else if (!this.taskValue) {
        return this.$message.error('请输入任务值');

      }
      console.log(type)
      if (!type) {
        this.$api.addTask(parms).then((res) => {
          this.loading = false;
          console.log('新增列表返回值：', res);
          // this.tableData = res.data.data;
          if (res.code == 0) {
            this.dialogVisible = false;
            this.getData(type)
          } else {
            this.$message.error(res.message)

          }
        }).catch((res) => {
          this.loading = false;
        });
      } else {
        this.$api.updateTask(parms).then((res) => {
          this.loading = false;
          console.log('更新任务返回值：', res);
          // this.tableData = res.data.data;
          if (res.code == 0) {
            this.dialogVisible = false;
            this.getData(type)
          } else {
            this.$message.error(res.message)
          }
        }).catch((res) => {
          this.loading = false;
        });
      }
    },
    // 关闭弹框
    handleClose() {
      // this.$refs['ruleForm'].resetFields();
      this.dialogVisible = false;
    },
    // 下拉框选择的数据
    async getRegionList(keyword) {
      const res = await getRegionOptionByKeyword(keyword != null && keyword.trim() != "" ? keyword.trim() : '');
      if (res.code == 200) {
        this.regionList = res.data;
      }
    },






    handleSizeChange(val) {
      this.pageSize = val
      console.log('pageSize----', val)

      // this.getData()
      this.divPage()

    },
    handleCurrentChange(val) {
      console.log('点击了----', val)
      this.page = val

      this.divPage()
    },
    userExport() {
      console.log(getToken())
      window.location.href = 'https://jingji-h5.ecps.com.cn/index.php?s=admin/getAwardList&isExport=1&token=' + getToken()
    }
  }
}
</script>
<style scoped>
.bodyBoxs {
  padding: 40px;
}

.boxs {
  width: 100%;
  background: #fff;
  border-radius: 15px;
  padding: 10px;
  min-height: 700px;
  overflow: hidden;

  .topBox {
    display: flex;
    justify-content: space-between;
  }
}
</style>
