<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      class="main-search"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="任务名称" prop="taskName">
        <el-input
          v-model="queryParams.taskName"
          placeholder="请输入任务名称"
          clearable
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务类型" prop="taskType">
        <el-select
          v-model="queryParams.taskType"
          placeholder="任务类型"
          clearable
          style="width: 150px"
        >
          <el-option label="完善资料" value="PROFILE" />
          <el-option label="观看广告" value="AD" />
          <el-option label="每日登录" value="LOGIN" />
          <el-option label="完成订单" value="ORDER" />
          <el-option label="发布作品" value="LOOK" />
          <el-option label="自定义" value="CUSTOM" />
        </el-select>
      </el-form-item>
      <el-form-item label="所属店铺" prop="storeId">
        <el-select
          v-model="queryParams.storeId"
          placeholder="所属店铺"
          clearable
          style="width: 180px"
        >
          <el-option
            :key="0"
            label="公共所有"
            v-if="!this.$store.getters.storeId"
            :value="0"
          />
          <el-option
            v-for="storeInfo in storeList"
            :key="storeInfo.id"
            :label="storeInfo.name"
            :value="storeInfo.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="状态"
          clearable
          style="width: 100px"
        >
          <el-option key="A" label="启用" value="A" />
          <el-option key="N" label="禁用" value="N" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['content:task:add']"
        >新增</el-button>
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="openImportDialog"
          v-hasPermi="['content:task:add']"
        >任务导入</el-button>
        <el-button
          type="success"
          plain
          icon="el-icon-tickets"
          size="mini"
          @click="openRecordDialog()"
          v-hasPermi="['content:task:index']"
        >完成记录</el-button>
      </el-form-item>
    </el-form>

    <el-table ref="tables" v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column label="ID" prop="id" width="70" />
      <el-table-column label="任务名称" align="center" prop="taskName" min-width="150" />
      <el-table-column label="任务编码" align="center" prop="taskCode" min-width="120" />
      <el-table-column label="任务类型" align="center" prop="taskType" width="110">
        <template slot-scope="scope">
          <el-tag size="mini" type="info">{{ getTaskTypeName(scope.row.taskType) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="所属店铺" align="center" prop="storeId">
        <template slot-scope="scope">
          <span v-if="scope.row.storeId && scope.row.storeId > 0">{{ getName(storeList, scope.row.storeId) }}</span>
          <span v-else>公共所有</span>
        </template>
      </el-table-column>
      <el-table-column label="奖励银币" align="center" prop="rewardPoint" width="100" />
      <el-table-column label="奖励余额(元)" align="center" prop="rewardBalance" width="120" />
      <el-table-column label="银币阈值" align="center" prop="pointThreshold" width="100" />
      <el-table-column label="余额阈值(元)" align="center" prop="balanceThreshold" width="120" />
      <el-table-column label="指定商品ID" align="center" prop="targetGoodsIds" min-width="140">
        <template slot-scope="scope">
          <span>{{ scope.row.targetGoodsIds || '全部商品' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="每日次数" align="center" prop="dailyLimit" width="100" />
      <el-table-column label="排序" align="center" prop="sort" width="80" />
      <el-table-column label="更新时间" align="center" prop="updateTime" width="170">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="A"
            inactive-value="N"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="220">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-tickets"
            v-hasPermi="['content:task:index']"
            @click="openRecordDialog(scope.row)"
          >完成记录</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-hasPermi="['content:task:edit']"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            v-hasPermi="['content:task:edit']"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="title" :visible.sync="open" class="common-dialog" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="任务名称" prop="taskName">
              <el-input v-model="form.taskName" placeholder="请输入任务名称" maxlength="100" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务编码" prop="taskCode">
              <el-input v-model="form.taskCode" placeholder="请输入任务编码" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="任务类型" prop="taskType">
              <el-select v-model="form.taskType" style="width: 100%" placeholder="请选择任务类型" @change="handleTaskTypeChange">
                <el-option label="完善资料" value="PROFILE" />
                <el-option label="观看广告" value="AD" />
                <el-option label="每日登录" value="LOGIN" />
                <el-option label="完成订单" value="ORDER" />
                <el-option label="发布作品" value="LOOK" />
                <el-option label="自定义" value="CUSTOM" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属店铺" prop="storeId">
              <el-select v-model="form.storeId" style="width: 100%" placeholder="所属店铺，空则公共所有">
                <el-option
                  :key="0"
                  label="公共所有"
                  v-if="!this.$store.getters.storeId"
                  :value="0"
                />
                <el-option
                  v-for="storeInfo in storeList"
                  :key="storeInfo.id"
                  :label="storeInfo.name"
                  :value="storeInfo.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="奖励银币" prop="rewardPoint">
              <el-input-number v-model="form.rewardPoint" :min="0" :max="99999" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="奖励余额(元)" prop="rewardBalance">
              <el-input-number v-model="form.rewardBalance" :min="0" :max="99999" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="银币阈值" prop="pointThreshold">
              <el-input-number v-model="form.pointThreshold" :min="0" :max="99999999" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="余额阈值(元)" prop="balanceThreshold">
              <el-input-number v-model="form.balanceThreshold" :min="0" :max="999999" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col v-if="isOrderTask" :span="12">
            <el-form-item label="指定商品ID" prop="targetGoodsIds">
              <el-input v-model="form.targetGoodsIds" placeholder="多个商品ID用英文逗号分隔；不填=全部商品" maxlength="500" />
            </el-form-item>
          </el-col>
          <el-col :span="isOrderTask ? 12 : 24">
            <el-form-item label="每日次数" prop="dailyLimit">
              <el-input-number v-model="form.dailyLimit" :min="1" :max="999" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="跳转链接" prop="jumpUrl">
              <el-input v-model="form.jumpUrl" placeholder="如：pages/user/index" maxlength="255" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="form.sort" :min="0" :max="9999" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="任务描述" prop="taskDesc">
              <el-input v-model="form.taskDesc" type="textarea" :rows="3" placeholder="请输入任务描述" maxlength="500" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio key="A" label="A" value="A">启用</el-radio>
                <el-radio key="N" label="N" value="N">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="导入公共任务"
      :visible.sync="importOpen"
      width="900px"
      append-to-body
      @close="closeImportDialog"
    >
      <el-form :inline="true" size="small">
        <el-form-item label="任务名称">
          <el-input
            v-model="importQuery.taskName"
            placeholder="请输入任务名称"
            clearable
            style="width: 200px"
            @keyup.enter.native="getPublicTasks"
          />
        </el-form-item>
        <el-form-item label="任务类型">
          <el-select v-model="importQuery.taskType" placeholder="任务类型" clearable style="width: 150px">
            <el-option label="完善资料" value="PROFILE" />
            <el-option label="观看广告" value="AD" />
            <el-option label="每日登录" value="LOGIN" />
            <el-option label="完成订单" value="ORDER" />
            <el-option label="发布作品" value="LOOK" />
            <el-option label="自定义" value="CUSTOM" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="getPublicTasks">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetImportQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table
        v-loading="importLoading"
        :data="publicTaskList"
        @selection-change="handleImportSelectionChange"
        max-height="420"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="任务名称" prop="taskName" min-width="180" />
        <el-table-column label="任务编码" prop="taskCode" min-width="140" />
        <el-table-column label="任务类型" align="center" prop="taskType" width="110">
          <template slot-scope="scope">
            <el-tag size="mini" type="info">{{ getTaskTypeName(scope.row.taskType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="奖励银币" align="center" prop="rewardPoint" width="100" />
        <el-table-column label="每日次数" align="center" prop="dailyLimit" width="100" />
        <el-table-column label="状态" align="center" prop="status" width="100">
          <template slot-scope="scope">
            <el-tag size="mini" :type="scope.row.status === 'A' ? 'success' : 'info'">
              {{ scope.row.status === 'A' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="importTotal > 0"
        :total="importTotal"
        :page.sync="importQuery.page"
        :limit.sync="importQuery.pageSize"
        @pagination="getPublicTasks"
      />

      <div slot="footer" class="dialog-footer">
        <el-button @click="closeImportDialog">取消</el-button>
        <el-button type="primary" :disabled="!importTaskIds.length" @click="handleImportSubmit">导入所选</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="任务完成记录"
      :visible.sync="recordOpen"
      width="1100px"
      append-to-body
      @close="closeRecordDialog"
    >
      <el-form
        :model="recordQuery"
        ref="recordQueryForm"
        size="small"
        :inline="true"
        label-width="80px"
      >
        <el-form-item label="任务名称" prop="taskName">
          <el-input
            v-model="recordQuery.taskName"
            placeholder="请输入任务名称"
            clearable
            style="width: 180px"
            @keyup.enter.native="getTaskRecordListData"
          />
        </el-form-item>
        <el-form-item label="会员号" prop="userNo">
          <el-input
            v-model="recordQuery.userNo"
            placeholder="请输入会员号"
            clearable
            style="width: 160px"
            @keyup.enter.native="getTaskRecordListData"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input
            v-model="recordQuery.mobile"
            placeholder="请输入手机号"
            clearable
            style="width: 160px"
            @keyup.enter.native="getTaskRecordListData"
          />
        </el-form-item>
        <el-form-item label="任务日期" prop="taskDate">
          <el-date-picker
            v-model="recordQuery.taskDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择任务日期"
            clearable
            style="width: 160px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleRecordQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetRecordQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="recordLoading" :data="recordList">
        <el-table-column label="ID" prop="id" width="70" />
        <el-table-column label="任务名称" prop="taskName" min-width="140" />
        <el-table-column label="任务编码" prop="taskCode" min-width="120" />
        <el-table-column label="会员号" prop="userNo" min-width="120" />
        <el-table-column label="称呼" prop="name" min-width="100" />
        <el-table-column label="手机号" prop="mobile" min-width="120" />
        <el-table-column label="任务日期" prop="taskDate" width="110" />
        <el-table-column label="完成次数" prop="completeNum" width="90" />
        <el-table-column label="领取次数" prop="claimNum" width="90" />
        <el-table-column label="最近完成时间" prop="lastCompleteTime" width="165">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.lastCompleteTime) || '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="最近领取时间" prop="lastClaimTime" width="165">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.lastClaimTime) || '--' }}</span>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="recordTotal > 0"
        :total="recordTotal"
        :page.sync="recordQuery.page"
        :limit.sync="recordQuery.pageSize"
        @pagination="getTaskRecordListData"
      />
    </el-dialog>
  </div>
</template>

<script>
import { getTaskList, getTaskInfo, saveTask, updateTaskStatus, getPublicTaskList, importPublicTask, getTaskRecordList } from '@/api/task'

export default {
  name: 'ContentTaskIndex',
  computed: {
    isOrderTask() {
      return this.form.taskType === 'ORDER'
    },
  },
  data() {
    return {
      loading: true,
      title: '',
      ids: [],
      multiple: true,
      showSearch: true,
      total: 0,
      list: [],
      open: false,
      storeList: [],
      form: {
        id: '',
        taskCode: '',
        taskName: '',
        taskType: 'CUSTOM',
        taskDesc: '',
        jumpUrl: '',
        rewardPoint: 0,
        rewardBalance: 0,
        pointThreshold: 0,
        balanceThreshold: 0,
        targetGoodsIds: '',
        completeThreshold: 0,
        dailyLimit: 1,
        storeId: 0,
        sort: 0,
        status: 'A',
      },
      queryParams: {
        page: 1,
        pageSize: 10,
        taskName: '',
        taskType: '',
        storeId: '',
        status: '',
      },
      importOpen: false,
      importLoading: false,
      publicTaskList: [],
      importTaskIds: [],
      importTotal: 0,
      importQuery: {
        page: 1,
        pageSize: 10,
        taskName: '',
        taskType: '',
      },
      recordOpen: false,
      recordLoading: false,
      recordList: [],
      recordTotal: 0,
      recordQuery: {
        page: 1,
        pageSize: 10,
        taskId: '',
        taskName: '',
        userNo: '',
        mobile: '',
        taskDate: '',
      },
      rules: {
        taskName: [{ required: true, message: '任务名称不能为空', trigger: 'blur' }],
        taskCode: [{ required: true, message: '任务编码不能为空', trigger: 'blur' }],
        taskType: [{ required: true, message: '任务类型不能为空', trigger: 'change' }],
      },
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getTaskTypeName(taskType) {
      const map = {
        PROFILE: '完善资料',
        AD: '观看广告',
        LOGIN: '每日登录',
        ORDER: '完成订单',
        LOOK: '发布作品',
        CUSTOM: '自定义',
      }
      return map[taskType] || taskType || '--'
    },
    handleTaskTypeChange() {
      if (this.form.taskType !== 'ORDER') {
        this.form.targetGoodsIds = ''
      }
    },
    getList() {
      this.loading = true
      getTaskList(this.queryParams).then((response) => {
        this.list = response.data.dataList.content
        this.total = response.data.dataList.totalElements
        this.storeList = response.data.storeList
        this.loading = false
      })
    },
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
      this.multiple = !selection.length
    },
    handleStatusChange(row) {
      let text = row.status == 'A' ? '启用' : '禁用'
      this.$modal
        .confirm('确认要' + text + '"' + row.taskName + '"吗？')
        .then(function () {
          return updateTaskStatus(row.id, row.status)
        })
        .then(() => {
          this.$modal.msgSuccess(text + '成功')
        })
        .catch(() => {
          row.status = row.status === 'N' ? 'A' : 'N'
        })
    },
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '新增任务'
    },
    openImportDialog() {
      this.importOpen = true
      this.importTaskIds = []
      this.importQuery.page = 1
      this.getPublicTasks()
    },
    getPublicTasks() {
      this.importLoading = true
      getPublicTaskList(this.importQuery).then((response) => {
        this.publicTaskList = response.data.dataList.content
        this.importTotal = response.data.dataList.totalElements
        this.importLoading = false
      }).catch(() => {
        this.importLoading = false
      })
    },
    resetImportQuery() {
      this.importQuery = {
        page: 1,
        pageSize: 10,
        taskName: '',
        taskType: '',
      }
      this.getPublicTasks()
    },
    closeImportDialog() {
      this.importOpen = false
      this.importLoading = false
      this.importTaskIds = []
    },
    openRecordDialog(row) {
      this.recordOpen = true
      this.recordQuery.page = 1
      if (row && row.id) {
        this.recordQuery.taskId = row.id
        this.recordQuery.taskName = row.taskName || ''
      } else {
        this.recordQuery.taskId = ''
        this.recordQuery.taskName = ''
      }
      this.getTaskRecordListData()
    },
    getTaskRecordListData() {
      this.recordLoading = true
      getTaskRecordList(this.recordQuery).then((response) => {
        this.recordList = response.data.dataList.content
        this.recordTotal = response.data.dataList.totalElements
        this.recordLoading = false
      }).catch(() => {
        this.recordLoading = false
      })
    },
    handleRecordQuery() {
      this.recordQuery.page = 1
      this.getTaskRecordListData()
    },
    resetRecordQuery() {
      this.recordQuery = {
        page: 1,
        pageSize: 10,
        taskId: '',
        taskName: '',
        userNo: '',
        mobile: '',
        taskDate: '',
      }
      this.getTaskRecordListData()
    },
    closeRecordDialog() {
      this.recordOpen = false
      this.recordLoading = false
      this.recordList = []
      this.recordTotal = 0
      this.recordQuery = {
        page: 1,
        pageSize: 10,
        taskId: '',
        taskName: '',
        userNo: '',
        mobile: '',
        taskDate: '',
      }
    },
    handleImportSelectionChange(selection) {
      this.importTaskIds = selection.map((item) => item.id)
    },
    handleImportSubmit() {
      if (!this.importTaskIds.length) {
        this.$modal.msgWarning('请先选择要导入的任务')
        return
      }
      const storeId = this.$store.getters.storeId || (this.queryParams.storeId === '' ? 0 : this.queryParams.storeId)
      importPublicTask({
        taskIds: this.importTaskIds,
        storeId,
      }).then((response) => {
        const importedCount = response.data.importedCount || 0
        const skippedCount = response.data.skippedCount || 0
        this.$modal.msgSuccess('导入完成：成功' + importedCount + '条，跳过' + skippedCount + '条')
        this.closeImportDialog()
        this.getList()
      })
    },
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getTaskInfo(id).then((response) => {
        this.form = response.data.taskInfo
        this.open = true
        this.title = '编辑任务'
      })
    },
    handleDelete(row) {
      const name = row.taskName
      this.$modal
        .confirm('是否确认删除"' + name + '"的数据项？')
        .then(function () {
          return updateTaskStatus(row.id, 'D')
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    reset() {
      this.form = {
        id: '',
        taskCode: '',
        taskName: '',
        taskType: 'CUSTOM',
        taskDesc: '',
        jumpUrl: '',
        rewardPoint: 0,
        rewardBalance: 0,
        pointThreshold: 0,
        balanceThreshold: 0,
        targetGoodsIds: '',
        completeThreshold: 0,
        dailyLimit: 1,
        storeId: 0,
        sort: 0,
        status: 'A',
      }
      this.resetForm('form')
    },
    cancel() {
      this.open = false
      this.reset()
    },
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (!valid) {
          return
        }
        if (this.form.taskType !== 'ORDER') {
          this.form.targetGoodsIds = ''
        }
        saveTask(this.form).then(() => {
          this.$modal.msgSuccess(this.form.id ? '修改成功' : '新增成功')
          this.open = false
          this.getList()
        })
      })
    },
  },
}
</script>
