<template>
  <a-modal
    v-model="visible"
    :width="1000"
    title="任务管理"
    @cancel="visible = false"
    @ok="visible = false"
  >
    <sd-data-table-ex
      ref="table"
      form-id="onlFormTimedTasks"
      page-id="online/task/onlFormTimedTasks"
      :columns="columns"
      show-selection
      :filter-expressions="expressions"
      :actions="actions"
      @detailModalShow="detailModalShow"
    >
      <template v-slot:form="{ model }">
        <sd-form-item name="name" />
        <sd-form-item name="code" />
        <sd-form-item name="des" />
        <sd-form-item name="moduleId" hidden :input-props="{ defaultValue: info.moduleId }" />
        <sd-form-item name="formId" hidden :input-props="{ defaultValue: info.formId }" />
        <sd-form-item name="sortNum" />
        <sd-form-item name="corn">
          <div :class="$style.corn">
            <a-input v-model="model.corn"></a-input>
            <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
            >
          </div>
        </sd-form-item>
        <SdCronCreate
          v-show="cronExpSetting"
          ref="cronCreate"
          :scheduler="scheduler"
          @setCronExpValue="setCronExpValue"
        />
        <sd-form-item name="attrFD" label="触发条件">
          <sd-formula-exps v-model="dataFilter" :fields="fields" />
        </sd-form-item>
        <div :class="['ant-form-item', $style.trigger]">
          <span class="ant-form-item-label">
            <label>触发事件</label>
          </span>
          <span :class="$style.btn">
            <a-button @click="delEvent">删除</a-button>
            <a-button type="primary" n @click="addEvent">新增</a-button>
          </span>
        </div>
        <div :class="$style.table">
          <sd-table
            row-key="id"
            :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
            :columns="eventColumns"
            sortable
            :data-source.sync="eventData"
            @update:data-source="setEventData"
          />
        </div>
      </template>
    </sd-data-table-ex>
  </a-modal>
</template>

<script>
import axios from '@/common/services/axios-instance'
import pickValues from '@/common/services/pick-values'
import sdListPickerVue from '@/common/components/sd-list-picker.vue'
import { scheduler } from '@/control-manage/util'
import formula2exps from '@/application-manage/formula-2-exps'
import PageService from '@/common/services/page-service'
import SdCronCreate from '@/control-manage/sd-cron-create.vue'
import TableColumnTypes from '@/common/services/table-column-types'
import TableActionTypes from '@/common/services/table-action-types'
import components from './_import-components/sd-task-manage-import'
const columns = [
  {
    title: '序号',
    dataIndex: 'sortNum',
  },
  {
    title: '任务名称',
    dataIndex: 'name',
    sdClickable: true,
  },
  {
    title: '任务编码',
    dataIndex: 'code',
  },
  {
    title: '创建时间',
    sdRender: TableColumnTypes.dateTime,
    dataIndex: 'creationTime',
  },
  {
    title: '状态',
    dataIndex: 'status',
    sdRender: TableColumnTypes.ex.switch,
  },
]
const eventColumns = [
  {
    title: '执行顺序',
    dataIndex: 'sortNum',
    customRender: (text, record, index) => `${index + 1}`,
  },
  {
    title: '事件名称',
    dataIndex: 'name',
  },
  {
    title: '事件编码',
    dataIndex: 'code',
  },
]
export default {
  name: 'SdTaskManage',
  metaInfo: {
    title: 'SdTaskManage',
  },
  components: { SdCronCreate, ...components },
  data() {
    return {
      scheduler,
      eventColumns,
      eventData: [],
      cronExpSetting: false,
      visible: false,
      info: {},
      selectedRowKeys: [],
      columns,
      fields: [],
      actions: [
        {
          label: '新建',
          id: 'new',
          type: TableActionTypes.ex.create,
        },
        {
          label: '删除',
          id: 'delete',
          type: TableActionTypes.ex.delete,
        },
      ],
      dataFilter: undefined,
    }
  },
  computed: {
    expressions() {
      return [
        {
          dataType: 'str',
          name: 'moduleId',
          op: 'like',
          stringValue: this.info.moduleId,
        },
      ]
    },
  },
  watch: {
    dataFilter(val) {
      this.$refs.table.getDetailModal().setFieldsValue({
        dataFilter: JSON.stringify(formula2exps(this.dataFilter)),
        attrFD: JSON.stringify(this.dataFilter),
      })
    },
  },
  methods: {
    formula2exps,
    addEvent() {
      pickValues(sdListPickerVue, {
        loadListData: () => {
          const params = {
            startPosition: 0,
            maxResults: -1,
            expressions: [
              {
                dataType: 'str',
                name: 'formId',
                op: 'eq',
                stringValue: this.info.formId,
              },
            ],
            formId: 'onlFormMethod',
            orderBy: 'sortNumber asc,creationTime desc',
            columns: 'id,methodCode,methodName',
          }
          return PageService.getList(params).then((res) => {
            return (res.data.data || []).map((d) => ({
              code: d.methodCode,
              name: d.methodName,
              id: d.id,
            }))
          })
        },
        disabledKeys: this.eventData.map((data) => data.id),
      }).then((values) => {
        this.eventData = [...values, ...this.eventData]
        this.setEventData()
      })
    },
    setEventData() {
      if (this.eventData.length) {
        this.$refs.table
          .getDetailModal()
          .setFieldValue(
            'triggerEvent',
            JSON.stringify(this.eventData.map((item, index) => ({ ...item, sortNum: index + 1 })))
          )
      }
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    delEvent() {
      this.eventData = this.eventData.filter((item) => !this.selectedRowKeys.includes(item.id))
      this.setEventData()
    },
    loadFrontEvents() {},
    show(info) {
      this.info = info
      this.visible = true
      axios
        .get(`api/framework/v1/we-app-form-list/show?appModuleId=${info.moduleId}`)
        .then((res) => {
          const data = res.data
          this.fields = data.onlListColumnDefs
            .filter((item) => item.searchConfigurable)
            .map((item) => {
              return {
                attr: item.fieldAttr,
                attrFD: item.fieldAttrFD,
                name: item.fieldId,
                caption: item.fieldName,
                dataType: item.fieldType.replace(/selectgroup|selectuser/, 'selectperson'),
              }
            })
          if (info.isFlow) {
            this.fields.push({
              name: 'FLOW_STATUS',
              caption: '流程状态',
              dataType: 'number',
            })
          }
        })
    },
    setCronExpValue(val) {
      this.$refs.table.getDetailModal().setFieldValue('corn', val)
    },
    detailModalShow() {
      setTimeout(() => {
        const attrFD = this.$refs.table.getDetailModal().getFieldValue('attrFD')
        this.dataFilter = attrFD ? JSON.parse(attrFD) : undefined
        this.eventData = JSON.parse(
          this.$refs.table.getDetailModal().getFieldValue('triggerEvent') || '[]'
        )
        this.selectedRowKeys = []
      }, 500)
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.corn {
  :global .ant-input {
    width: 82%;
    margin-right: 5px;
  }
}
.trigger {
  margin-bottom: 0;
  .btn {
    display: inline-block;
    width: 80%;
    text-align: right;
    :global .ant-btn {
      margin: 5px;
    }
  }
}

.table {
  padding: 0 10px;
}
</style>
