<template>
  <div>
    <page-view :title="false">
      <div slot="headerContent">
      </div>
      <a-card :bordered="false">
        <div class="group-list">
          <div class="group-header">
            <a-row type="flex" justify="space-between">
              <a-col :span="14">
                <div class="header-title">任务分组</div>
                <!-- <a-button @click="showGroupModal">新建分组</a-button>-->
              </a-col>
              <a-col :span="10" style="text-align: right;">
                <!--<a-button type="primary" @click="toTaskSetting">新建模板</a-button>-->
              </a-col>
            </a-row>
          </div>
          <div class="group-list-item">
            <group-list
              :list="templateList"
              @deploymentTask="deploymentTask"
              @editTask="editTask"
              @toggleTaskStatus="toggleTaskStatus"
              @editGroup="editGroup"
              @deleteGroup="deleteGroup"
              @moveTask="moveTask"
              @copyTask="copyTask"
              @pushTask="pushTask"
            ></group-list>
          </div>
        </div>
      </a-card>
    </page-view>
    <a-modal
      title="新建分组"
      :visible="groupModalVisible"
      @cancel="handleGroupCancel"
      @ok="handleGroupSubmit"
    >
      <a-form
        id="components-form-demo-validate-other"
        :form="form"
        @submit="handleGroupSubmit"
      >
        <a-form-item
          label="分组名称"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
        >
          <a-input
            v-decorator="[
              'workTpNm',
              {rules: [{ required: true, message: '请输入分组名称！' }]}
            ]"
          />
        </a-form-item>
        <a-form-item
          :wrapper-col="{ span: 12, offset: 6 }"
        >
          <!--<a-button-->
          <!--  type="primary"-->
          <!--  html-type="submit"-->
          <!--  :loading="groupModalConfirmLoading"-->
          <!--&gt;-->
          <!--  提交-->
          <!--</a-button>-->
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal
      title="修改分组"
      :visible="groupModalVisible2"
      @cancel="handleGroupCancel2"
      @ok="handleGroupSubmit2"
    >
      <a-form
        id="components-form-demo-validate-other"
        :form="form2"
        @submit="handleGroupSubmit2"
      >
        <a-form-item
          label="分组名称"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
        >
          <a-input
            v-decorator="[
              'workTpNm',
              {rules: [{ required: true, message: '请输入分组名称！' }]}
            ]"
          />
        </a-form-item>
        <a-form-item
          style="display: none;"
          label="分组ID"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
        >
          <a-input
            v-decorator="[
              'workTpId'
            ]"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal
      :title="copyOrMoveModalTitle[copyOrMoveModalTitleIndex]"
      :visible="copyOrMoveModalVisible"
      @cancel="handleCopyOrMoveModalCancel"
      @ok="handleCopyOrMoveModalSubmit"
      okText="确认"
      cancelText="取消"
    >
      <a-form
        id="components-form-demo-validate-other"
        :form="copyOrMoveModalForm"
        @submit="handleCopyOrMoveModalSubmit"
      >
        <a-form-item
          label="任务模板分组">
          <a-select
            placeholder="请选择"
            v-decorator="[
              'workTpId',
              {rules: [{ required: true, message: '请输入标题' }]}
            ]">
            <a-select-option value="" disabled>请选择</a-select-option>
            <a-select-option v-for="(item, index) in groupList" :value="item.id">{{ item.name }}</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal
      title="提示"
      :visible="pushATask"
      @ok="commitPushTask"
      @cancel="pushATask = false"
    >
      <p>是否确定发布</p>
    </a-modal>
  </div>
</template>

<script>
  import { PageView } from '@/layouts';
  import ARow from 'ant-design-vue/es/grid/Row';
  import GroupList from './components/group-list';
  import {
    deployProcess,
    createWorkGroup,
    getAllTemplatesWithGroup,
    getTemplateId,
    updateWorkTemplateStatus,
    deleteGroupById,
    updateGroupById,
    getGroupList,
    copyOrMoveTemplate,
    pushTaskById
  } from '@/api/task';
  import { mapActions } from 'vuex';

  export default {
    name: 'taskGrouping',
    components: {
      ARow,
      PageView,
      GroupList
    },
    data() {
      return {
        pushATask: false,
        templateList: [],
        form: this.$form.createForm(this),
        groupModalVisible: false,
        groupModalConfirmLoading: false,
        form2: this.$form.createForm(this),
        groupModalVisible2: false,
        copyOrMoveModalTitle: ['复制模板', '移动模板'],
        copyOrMoveModalTitleIndex: 0,
        copyOrMoveModalTaskId: '',
        copyOrMoveModalVisible: false,
        copyOrMoveModalForm: this.$form.createForm(this),
        groupList: [],
        pushId: '',
        workTpId: ''
      };
    },
    methods: {
      ...mapActions(['CleanTempletBytempId', 'QueryTempletBytempId','GetUserToken']),
      commitPushTask() {
        pushTaskById({id:this.pushId,workTpId:this.workTpId,typeTemplate:this.typeTemplate})
          .then((res) => {
            this.pushATask = false
            if ('发布成功' === res.msg) {
              this.templateList.forEach(item => {
                if (item.workTpId === this.workTpId) {
                  item.templateList.forEach(child => {
                    if (child.id === this.pushId) {
                      child.status = '1'
                    }
                  })
                }
              })
            }
            this.workTpId = ''
            this.pushId = ''
          })
      },
      pushTask(params) {
        this.pushATask = true
        this.pushId = params.id
        this.workTpId = params.workTpId
        this.typeTemplate = params.typeTemplate
      },
      toTaskSetting() {
        const templateId = Number(Number(Math.random().toString().substr(3, 30)) + Date.now()).toString(32);
        this.CleanTempletBytempId()
          .then(() => {
            this.$router.push({
              path: '/taskSetting',
              query: { templateId: templateId, templateName: '任务模板名称' }
            });
          });
      },
      /**
       * 获得包含分组模板列表
       */
      getAllTemplatesWithGroup() {
        getAllTemplatesWithGroup()
          .then((res) => {
            const data = res.data || [];
            this.templateList = data.map((item) => {
              return Object.assign({}, {
                workTpId: item.id || '',
                workTpNm: item.name || '',
                templateList: item.templateList || [],
                ifEnable: item.ifEnable || ''
              });
            });
            console.log('a', this.templateList);
          })
          .catch((err) => {
            console.error(err);
          });
      },
      deploymentTask(id) {
        console.log('task', id);
        const data = {
          templateId: id
        };
        deployProcess(data)
          .then((res) => {
            if (res.code === 'M0000') {
              // 通知框
              this.$notification['success']({
                message: '部署成功',
                description: res.msg,
                onClick: () => {
                  console.log('Notification Clicked!');
                }
              });
            } else {
              // 通知框
              this.$notification['warning']({
                message: '部署失败',
                description: res.msg,
                onClick: () => {
                  console.log('Notification Clicked!');
                }
              });
            }
          });
      },
      editTask(id) {
        console.log('task', id);
        const data = {
          templateId: id
        };
        this.QueryTempletBytempId(data)
          .then(res => {
            const templateId = res.data.workTemplate.id;
            const templateName = res.data.workTemplate.templateNm;
            this.$router.push({
              path: '/taskSetting',
              query: { templateId, templateName }
            });
          });
      },
      /**
       * 新增分组表单提交
       */
      handleGroupSubmit(e) {
        e.preventDefault();
        this.groupModalConfirmLoading = true;
        this.form.validateFields((err, values) => {
          if (!err) {
            console.log('Received values of form: ', values);
            const data = {
              name: values.workTpNm
            };
            createWorkGroup(data)
              .then((res) => {
                this.groupModalConfirmLoading = false;
                setTimeout(() => {
                  this.groupModalVisible = false;
                }, 500);
                this.getAllTemplatesWithGroup();
                this.$notification['success']({
                  message: '新增分组成功',
                  description: res.msg,
                  onClick: () => {
                    console.log('Notification Clicked!');
                  }
                });
              })
              .catch((err) => {
                this.groupModalConfirmLoading = false;
                this.$notification['warning']({
                  message: '新增分组失败',
                  description: err.msg,
                  onClick: () => {
                    console.log('Notification Clicked!');
                  }
                });
              });
          }
        });
      },
      handleGroupCancel() {
        this.groupModalVisible = false;
      },
      showGroupModal() {
        this.groupModalVisible = true;
        this.groupModalConfirmLoading = false;
      },
      /**
       * 修改任务模板状态
       * 1：启用 0：停用
       */
      toggleTaskStatus(data) {
        console.log(data);
        const d = {
          id: data.id,
          ifEnable: data.status
        };
        const message = data.status === 0 ? '停用成功' : '启用成功';
        updateWorkTemplateStatus(d)
          .then(res => {
            if (res.code === 'M0000') {
              this.getAllTemplatesWithGroup();
              this.$notification['success']({
                message
              });
            }
          });
      },
      deleteGroup(id) {
        deleteGroupById(id)
          .then(res => {
            if (res.code === 'M0000') {
              this.getAllTemplatesWithGroup();
              this.$notification['success']({
                message: '删除分组成功',
                description: res.msg
              });
            } else {
              this.$notification['warning']({
                message: res.msg,
                description: res.msg
              });
            }
          })
          .then(err => {
            this.$notification['warning']({
              message: '删除分组失败',
              description: err.msg
            });
          });
      },
      editGroup(groupItem) {
        this.groupModalConfirmLoading = false;
        this.groupModalVisible2 = true;
        const field = {
          workTpId: groupItem.workTpId || '',
          workTpNm: groupItem.workTpNm || '',
          ifEnable: groupItem.ifEnable || ''
        };
        this.$nextTick(() => {
          this.form2.setFieldsValue(field);
        });
      },
      handleGroupCancel2() {
        this.groupModalVisible2 = false;
      },
      /**
       * 修改分组表单提交
       */
      handleGroupSubmit2(e) {
        e.preventDefault();
        this.groupModalConfirmLoading = true;
        this.form2.validateFields((err, values) => {
          if (!err) {
            console.log('Received values of form: ', values);
            const data = new FormData();
            data.append('id', values.workTpId);
            data.append('ifEnable', values.ifEnable);
            data.append('name', values.workTpNm);
            updateGroupById(data)
              .then((res) => {
                this.groupModalConfirmLoading = false;
                setTimeout(() => {
                  this.groupModalVisible2 = false;
                }, 500);
                this.getAllTemplatesWithGroup();
                this.$notification['success']({
                  message: '修改分组成功',
                  description: res.msg,
                  onClick: () => {
                    console.log('Notification Clicked!');
                  }
                });
              })
              .catch((err) => {
                this.groupModalConfirmLoading = false;
                this.$notification['warning']({
                  message: '修改分组失败',
                  description: err.msg,
                  onClick: () => {
                    console.log('Notification Clicked!');
                  }
                });
              });
          }
        });
      },
      getGroupList() {
        getGroupList()
          .then((res) => {
            this.groupList = res.data || [];
          })
          .catch((err) => {
            console.error(err);
          });
      },
      moveTask(id) {
        this.getGroupList();
        this.copyOrMoveModalTaskId = id;
        this.copyOrMoveModalTitleIndex = 1;
        this.groupModalConfirmLoading = false;
        this.copyOrMoveModalVisible = true;
        this.$nextTick(() => {
          this.copyOrMoveModalForm.resetFields();
        });
      },
      copyTask(id) {
        this.getGroupList();
        this.copyOrMoveModalTaskId = id;
        this.copyOrMoveModalTitleIndex = 0;
        this.groupModalConfirmLoading = false;
        this.copyOrMoveModalVisible = true;
        this.$nextTick(() => {
          this.copyOrMoveModalForm.resetFields();
        });
      },
      handleCopyOrMoveModalCancel() {
        this.copyOrMoveModalVisible = false;
      },
      /**
       * 移动或复制任务提交表单
       */
      handleCopyOrMoveModalSubmit(e) {
        e.preventDefault();
        this.groupModalConfirmLoading = true;
        this.copyOrMoveModalForm.validateFields((err, values) => {
          if (!err) {
            console.log('Received values of form: ', values);
            const data = new FormData();
            data.append('workTpId', values.workTpId);
            data.append('templateId', this.copyOrMoveModalTaskId);

            copyOrMoveTemplate(data, this.copyOrMoveModalTitleIndex)
              .then((res) => {
                this.groupModalConfirmLoading = false;
                setTimeout(() => {
                  this.copyOrMoveModalVisible = false;
                }, 500);
                this.getAllTemplatesWithGroup();
                this.$notification['success']({
                  message: this.copyOrMoveModalTitle[this.copyOrMoveModalTitleIndex] + '成功',
                  description: res.msg,
                  onClick: () => {
                    console.log('Notification Clicked!');
                  }
                });
              })
              .catch((err) => {
                this.groupModalConfirmLoading = false;
                this.$notification['warning']({
                  message: this.copyOrMoveModalTitle[this.copyOrMoveModalTitleIndex] + '失败',
                  description: err.msg,
                  onClick: () => {
                    console.log('Notification Clicked!');
                  }
                });
              });
          }
        });
      }
    },
    async mounted() {
      await this.GetUserToken();
      console.log('222222222222222222222222222222222');
      this.getAllTemplatesWithGroup();
    }
  };
</script>

<style lang="less" scoped>
  .group-list {
    background: #ffffff;
    height: 100%;

    .group-header {
      margin-bottom: 10px;
    }

    .header-title {
      display: inline-block;
      font-size: 18px;
      padding-right: 30px;
    }
  }

</style>
