<template>
  <div>
    <div :class="$style.addButton"
      ><a-button v-if="!readonly" type="primary" @click="showAddTask('add')"
        >新建任务</a-button
      ></div
    >
    <a-table
      :columns="columns"
      :data-source="model.jobName ? [model] : []"
      :row-key="(record, index) => index"
      :pagination="false"
    >
      <template slot="lastExecuteStatus" slot-scope="text, record">
        <!-- <template v-for="(item, key) in statusList">
          <span v-if="text === item.value || text === parseInt(item.value)" :key="key">{{
            item.label
          }}</span>
        </template> -->
        <span v-if="record.lastExecuteStatus === 1">执行中</span>
        <span v-else-if="record.lastExecuteStatus === 2">执行成功</span>
        <span v-else-if="record.lastExecuteStatus === 0">执行失败</span>
        <span v-else>暂未执行</span>
      </template>
      <!-- 时间戳转化成年月日时分秒 -->
      <template slot="jobCreationTime" slot-scope="text, record">
        <span>{{ new Date(record.jobCreationTime).toLocaleString() }}</span>
      </template>
      <template slot="jobCreatorName" slot-scope="text, record">
        <span>{{ record.jobCreatorName }}</span>
      </template>
      <template slot="action" slot-scope="text, record">
        <!-- 编辑 执行 立即执行 执行记录 查看数据 删除 -->
        <a-button v-if="!readonly" type="link" @click="showEditOrData(record.id)">编辑</a-button>
        <a-button v-if="record.jobStatus === 1" type="link" @click="execute(record.id, 'stop')"
          >暂停任务</a-button
        >
        <a-button v-else type="link" @click="execute(record.id)">恢复任务</a-button>
        <a-button v-if="isShowEmm" type="link" @click="executeNow(record.id)">立即执行</a-button>
        <a-button type="link" @click="executeRecord(record.id)">执行记录</a-button>
        <a-button type="link" @click="viewData(record.id)">查看数据</a-button>
        <a-button v-if="!readonly" type="link" @click="deleteData(record.id)">删除</a-button>
      </template>
    </a-table>
    <!-- 新建任务 -->
    <a-modal
      v-model="addTask"
      :title="(modalTitle === 'add' ? '新增' : '编辑') + '任务'"
      width="700px"
      :confirm-loading="confirmLoading"
      @ok="addJob"
      @cancel="cancelAddTask"
    >
      <div :class="$style.content">
        <a-form-model
          ref="formValidate"
          :model="form"
          :label-col="{ span: 3 }"
          :wrapper-col="{ span: 12 }"
          :rules="rules"
        >
          <div :class="$style.tip"
            >提示：模型新建跑批任务后，将不能修改模型逻辑及参数，修改后取数任务将出现失败，逻辑及参数变化需新建模型。</div
          >
          <a-form-model-item label="任务名称" prop="jobName">
            <!-- <a-input v-model="form.jobName" :disabled="modalTitle !== 'add'" /> -->
            <a-input v-model="form.jobName" :disabled="true" />
          </a-form-model-item>
          <a-tabs v-model="form.jobType" @change="tabscallback">
            <a-tab-pane :key="0" tab="全量" :disabled="tabsdisabled">
              <!-- 拉取频率 -->
              <!-- cron表达式 -->
              <a-form-model-item
                label="cron表达式"
                placeholder="请输入cron表达式"
                prop="cronExpression"
              >
                <a-row :gutter="24">
                  <a-col :span="14">
                    <a-input v-model="form.cronExpression"></a-input>
                  </a-col>
                  <a-col :span="10">
                    <a-button
                      v-show="!cronExpSetting"
                      :class="$style.formBtn"
                      @click="
                        () => {
                          cronExpSetting = true
                        }
                      "
                      >高级设置</a-button
                    >
                    <a-button
                      v-show="cronExpSetting"
                      :class="$style.formBtn"
                      @click="
                        () => {
                          cronExpSetting = false
                        }
                      "
                      >收起</a-button
                    >
                  </a-col>
                </a-row>
                <SdCronCreate
                  v-show="cronExpSetting"
                  ref="cronCreate"
                  :scheduler="scheduler"
                  @setCronExpValue="setCronExpValue"
                ></SdCronCreate>
              </a-form-model-item>

              <!-- 任务有效期 -->
              <a-form-model-item label="任务有效期" prop="jobValidSt">
                <a-range-picker v-model="form.jobTime" @change="jobTimeChange" />
              </a-form-model-item>
            </a-tab-pane>
            <a-tab-pane :key="1" tab="增量">
              <!-- cron表达式 -->
              <a-form-model-item
                label="cron表达式"
                placeholder="请输入cron表达式"
                prop="cronExpression"
              >
                <a-row :gutter="24">
                  <a-col :span="14">
                    <a-input v-model="form.cronExpression"></a-input>
                  </a-col>
                  <a-col :span="10">
                    <a-button
                      v-show="!cronExpSetting"
                      :class="$style.formBtn"
                      @click="
                        () => {
                          cronExpSetting = true
                        }
                      "
                      >高级设置</a-button
                    >
                    <a-button
                      v-show="cronExpSetting"
                      :class="$style.formBtn"
                      @click="
                        () => {
                          cronExpSetting = false
                        }
                      "
                      >收起</a-button
                    >
                  </a-col>
                </a-row>
                <SdCronCreate
                  v-show="cronExpSetting"
                  ref="cronCreate"
                  :scheduler="scheduler"
                  @setCronExpValue="setCronExpValue"
                ></SdCronCreate>
              </a-form-model-item>
              <!-- 任务有效期 -->
              <a-form-model-item label="任务有效期" prop="jobValidSt">
                <a-range-picker v-model="form.jobTime" @change="jobTimeChange" />
              </a-form-model-item>
              <!-- 是否开启下发 显示是 1否 0  distributeFlag-->
              <a-form-model-item v-if="model.modelType !== '0'" label="是否开启下发">
                <a-radio-group v-model="form.distributeFlag">
                  <a-radio :value="0">否</a-radio>
                  <a-radio :value="1">是</a-radio>
                </a-radio-group>
              </a-form-model-item>
              <!--添加定时任务那是 distributeSt  传时间戳  -->
              <!-- 期初数据判断  distributeSt-->
              <a-form-model-item v-if="form.distributeFlag === 1" label="期初数据判断">
                <a-date-picker v-model="form.distributeSt" formt="YYYY-MM-DD" />
              </a-form-model-item>
            </a-tab-pane>
          </a-tabs>
        </a-form-model>
      </div>
    </a-modal>

    <!-- 执行状态 -->
    <a-modal v-model="executeRecordShow" title="执行记录" width="700px">
      <div :class="$style.content">
        <!-- <a-table
          :columns="executeRecordTable.columns"
          :data-source="executeRecordTable.dataSource"
        ></a-table> -->
        <SdDataTableEx
          form-id="iamModelJobStatus"
          page-id="audit/maintain/iamModelJobStatus"
          :filter-expressions="expressions"
          :columns="recordColumns"
        >
          <!-- 执行状态 -->
          <template slot="status" slot-scope="text, record">
            <span>{{
              record.status === 1 ? '执行中' : record.status === 2 ? '执行成功' : '执行失败'
            }}</span>
          </template>
        </SdDataTableEx>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { message, Modal } from 'ant-design-vue'
import AuditMaintainService from './audit-maintain-service'
import SdCronCreate from '@/control-manage/sd-cron-create.vue'
import { scheduler } from '@/control-manage/util'
import moment from 'moment'
import TableColumnTypes from '@/common/services/table-column-types'
import SdDataTableEx from '@/common/components/sd-data-table-ex.vue'

export default {
  name: 'AuditRegularTime',
  metaInfo: {
    title: 'AuditRegularTime',
  },
  components: {
    SdCronCreate,
    SdDataTableEx,
  },
  props: {
    model: {
      type: Object,
      default: () => ({}),
      // onreset
    },
    // 是否只读
    readonly: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      isShowEmm: false,
      // 任务名称 策略配置 最后一次执行状态 创建时间 创建人 操作（需要插槽）
      expressions: [{ dataType: 'str', name: 'modelId', op: 'eq', stringValue: '' }],
      recordColumns: [
        {
          title: '序号',
          dataIndex: 'sort',
          customRender: (text, record, index) => `${index + 1}`,
        },
        {
          title: '执行时间',
          dataIndex: 'creationTime',
          sdRender: TableColumnTypes.dateTime,
        },
        {
          title: '执行状态',
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' },
        },
        // 失败原因
        // errMsg
        {
          title: '失败原因',
          dataIndex: 'errMsg',
        },
      ],
      columns: [
        {
          title: '任务名称',
          dataIndex: 'jobName',
          key: 'jobName',
        },
        {
          title: '策略配置',
          dataIndex: 'cronExp',
          key: 'cronExp',
        },
        {
          title: '最后一次执行状态',
          dataIndex: 'lastExecuteStatus',
          key: 'lastExecuteStatus',
          scopedSlots: { customRender: 'lastExecuteStatus' },
        },
        {
          title: '创建时间',
          dataIndex: 'jobCreationTime',
          key: 'jobCreationTime',
          scopedSlots: { customRender: 'jobCreationTime' },
        },
        {
          title: '创建人',
          dataIndex: ' jobCreatorName',
          key: ' jobCreatorName',
          scopedSlots: { customRender: 'jobCreatorName' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          key: 'action',
          scopedSlots: { customRender: 'action' },
        },
      ],
      dataSource: [],
      scheduler,
      // 执行状态：  执行中 执行成功 执行失败
      statusList: [
        { label: '执行中', value: '1' },
        { label: '执行成功', value: '2' },
        { label: '执行失败', value: '0' },
        // 暂未执行
        { lable: '暂未执行', value: '10' },
      ],

      tabsdisabled: false,
      modalTitle: 'add',
      addTask: false,
      rules: {
        jobName: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
        cronExpression: [{ required: true, message: '请输入cron表达式', trigger: 'blur' }],
        jobValidSt: [{ required: true, message: '请选择任务有效期', trigger: 'blur' }],
        // 任务有效期
      },
      confirmLoading: false,
      form: {
        // String jobName; // 任务名称 默认为模型名称
        jobName: '',
        // 任务分组名称 jobGroupName 默认为模型编号
        jobGroupName: '',
        // 任务类型 0 全 1增 jobType
        jobType: 0,
        // 任务有效期：
        jobTime: [],
        // 任务有效开始时间
        jobValidSt: '',
        // 任务有效结束时间
        jobValidEd: '',
        // cron 表达式
        cronExpression: '',
        // 是否下发
        distributeFlag: 0,
        distributeSt: null,
        //
      },
      cronExpSetting: false,

      // 执行记录
      executeRecordShow: false,
      // 执行记录表格
      executeRecordTable: {
        columns: [
          // 序号
          {
            title: '序号',
            dataIndex: 'sort',
          },
          {
            title: '执行时间',
            dataIndex: 'executeTime',
            key: 'executeTime',
          },
          {
            title: '执行状态',
            dataIndex: 'executeStatus',
            key: 'executeStatus',
          },
        ],
        dataSource: [
          {
            sort: 1,
            executeTime: '执行时间',
            executeStatus: '执行成功',
          },
        ],
        tableStatus: '',
      },
      //
    }
  },
  computed: {
    comData() {
      return this.tableStatus === '正常'
    },
  },
  watch: {
    model: {
      handler(val) {
        this.dataSource = val
      },
      deep: true,
    },
  },
  created() {
    // 查询当前状态
    // G_1_EXECUTE_IMMEDIATELY
    const roles = this.$store.state.sd.common.userInfo.default.roles
    this.isShowEmm = roles.map((val) => val.code).includes('G-1_EXECUTE_IMMEDIATELY')
  },

  methods: {
    // 显示编辑
    showEditOrData(id) {
      // this.showAddTask('edit')
      this.form.cronExpression = this.model.cronExpression
      this.form.jobName = this.model.jobName
      this.form.jobGroupName = this.model.jobGroupName
      this.form.jobValidSt = this.model.jobValidSt
      this.form.jobValidEd = this.model.jobValidEd
      // moment(this.model.jobValidSt, 'YYYY-MM-DD'),
      // moment(this.model.jobValidEd, 'YYYY-MM-DD'),
      // 时间戳转moment格式
      this.form.jobTime = [moment(this.model.jobValidSt), moment(this.model.jobValidEd)]
      this.form.id = this.model.id
      this.form.distributeFlag = this.model.distributeFlag
      this.form.jobType = parseInt(this.model.jobType)
      // 如果有则赋值
      this.form.distributeSt = this.model.distributeSt ? moment(this.model.distributeSt) : null
      this.modalTitle = 'edit'
      this.addTask = true
    },

    // 新建任务
    addJob() {
      this.$refs.formValidate.validate((valid) => {
        if (valid) {
          this.confirmLoading = true
          const params = {
            jobName: this.form.jobName,
            jobGroupName: this.form.jobGroupName,
            id: this.model.id,
            distributeFlag: this.form.distributeFlag,
            jobValidEd: this.form.jobValidEd,
            jobValidSt: this.form.jobValidSt,
            distributeSt: null,
          }
          params.distributeSt = this.form.distributeSt ? this.form.distributeSt._d.getTime() : null
          params.cronExpression = this.form.cronExpression
          if (this.form.jobType === 0) {
            params.jobType = 0
          } else {
            params.jobType = 1

            // 增量字段
            // 是否下发
          }
          if (this.modalTitle === 'add') {
            AuditMaintainService.addTask(params).then((res) => {
              // 新建成功
              message.success('新建成功')
              setTimeout(() => {
                window.location.reload()
              }, 500)
              this.addTask = false
            })
          } else {
            AuditMaintainService.rescheduleJob(params).then((res) => {
              // if (res.code === 200) {
              //   this.form = res.data
              // }
              // 更新成功
              message.success('更新成功')
              this.$emit('onreset')
              // 两秒后刷新页面
              setTimeout(() => {
                window.location.reload()
              }, 500)
              this.showAddTask('edit')
              // 关闭当前
            })
          }
        }
      })
    },

    // 任务有效期变化
    jobTimeChange(val) {
      // 设置

      // 获取时间戳
      this.form.jobValidSt = val[0]._d.getTime()
      this.form.jobValidEd = val[1]._d.getTime()
    },
    cancelAddTask() {
      this.addTask = false
      // 清空表单
      this.form = {
        jobName: '',
        jobGroupName: '',
        jobType: 0,
        jobTime: null,
        jobValidSt: '',
        jobValidEd: '',
        cronExpression: '',
        distributeFlag: 0,
        distributeSt: null,
      }
    },
    // 设置cron表达式的值
    setCronExpValue(val) {
      // this.$refs.createForm.setFieldValue('cronExp', val)
      this.form.cronExpression = val
    },
    execute(id, type) {
      const params = {
        id,
        jobName: this.model.jobName,
      }
      if (type === 'stop') {
        Modal.confirm({
          title: '确认停止',
          content: '确认停止该任务吗？',
          okText: '确认',
          cancelText: '取消',
          onOk() {
            // 停止
            AuditMaintainService.pauseJob(params).then((res) => {
              message.success('暂停成功')
              setTimeout(() => {
                window.location.reload()
              }, 500)
            })
          },
        })
        return
      }
      AuditMaintainService.resumeJob(params).then((res) => {
        message.success('恢复成功')
        setTimeout(() => {
          window.location.reload()
        }, 500)
      })
    },
    executeNow(id) {
      const params = {
        id,
        jobName: this.model.jobName,
      }
      Modal.confirm({
        title: '立即执行',
        content: '当前模型存在执行任务，手动执行可能出现重复数据，是否要手动执行？',
        okText: '确认',
        cancelText: '取消',
        onOk() {
          AuditMaintainService.executeJob(params).then((res) => {
            message.success('立即执行成功')
            setTimeout(() => {
              // window.location.reload()
            }, 500)
          })
        },
      })
    },
    executeRecord(id) {
      // 获取执行记录
      this.expressions[0].stringValue = id
      this.executeRecordShow = true
    },
    viewData(id) {
      // 如果有且只有一个？号则直接跳转

      const url = window.location.href
      const urlArr = url.split('?')
      if (urlArr.length === 3) {
        const baseUrl = urlArr[0]
        window.open(baseUrl + `#/audit-sq-record?id=${id}`)
        return
      }

      // const url = window.location.href
      // const index = url.indexOf('?')
      // const baseUrl = url.substring(0, index)
      window.open(`#/audit-sq-record?id=${id}`)
    },
    deleteData(id) {
      const params = {
        id,
        jobName: this.model.jobName,
      }
      // 确认删除
      Modal.confirm({
        title: '确认删除',
        content: '确认删除该任务吗？',
        okText: '确认',
        cancelText: '取消',
        onOk() {
          // 删除
          AuditMaintainService.deleteJob(params).then((res) => {
            // 删除成功
            message.success('删除成功')
            // 刷新页面
            window.location.reload()
          })
        },
      })
    },
    tabscallback(key) {
      // 如果key ==0 则保留 corn 和开始结束时间
      // 如果key === 0 则下发为0
      if (key === '0') {
        this.form.distributeFlag = 0
      }
    },
    // 当前的模型类型
    showAddTask(type = 'add') {
      // 如果已经jobName存在则提示已存在定时任务
      if (this.model.jobName && type === 'add') {
        message.error('已存在定时任务')
        return
      }
      if (type === 'add') {
        this.form.jobName = this.model.modelCode + '-' + this.model.modelName
      }
      this.modalTitle = type
      this.form.jobGroupName = this.model.modelCode
      // 请选择模型类型后重试
      if (!this.model.modelType) {
        message.error('请选择模型类型后重试')
        return
      }
      // 只有分析类可以两者都选
      if (this.model.modelType + '' === '0') {
        this.tabsdisabled = false
        this.form.jobType = 0
        this.form.distributeFlag = 0
        // 下发标识=0
      } else {
        this.form.distributeFlag = 0

        this.tabsdisabled = true
        this.form.jobType = 1
      }
      this.addTask = !this.addTask
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.add-button {
  // 居右
  text-align: right;
}
.onflex {
  display: flex;
  align-items: center;
}
.tip {
  margin-left: 42px;
  color: $alert-error-icon-color;
}
</style>
