<template>
  <div>
    <div class="i-layout-page-header">
      <PageHeader :title="$route.meta.title" :content="$route.meta.description" hidden-breadcrumb />
    </div>
    <Card :bordered="false" dis-hover class="ivu-mt">
      <view-table ref="table" v-if="page" @create="create">
        <template slot-scope="{ row }" slot="command">
          <Button
            size="small"
            v-if="row.application.status != 'Draft' && row.application.status != 'Rejected'"
            :title="$t('Front_Btn_Detail')"
            type="info"
            custom-icon="fa fa-file-alt"
            @click="$refs.showForm.open(row)"
          ></Button>
          <Button
            size="small"
            v-if="(row.application.status == 'Draft' || row.application.status == 'Rejected') && row.application.applicantID == info.id"
            :title="$t('Front_Btn_Edit')"
            type="primary"
            custom-icon="fa fa-edit"
            @click="$refs.form.open(row)"
          ></Button>
        </template>
      </view-table>
    </Card>
    <modal-form ref="form" v-if="page" @on-after-save="$refs.table.loadData()">
      <template slot="footer">
        <span></span>
        <Button type="primary" custom-icon="fa fa-cloud-upload-alt" @click="submit">{{ $t('Front_Btn_Submit') }}</Button>
        <Button type="primary" custom-icon="fa fa-save" @click="save">{{ $t('Front_Btn_Save') }}</Button>
        <Button
          type="warning"
          v-if="
            $refs.form &&
            $refs.form.data &&
            $refs.form.data.application &&
            $refs.form.data.applicationID &&
            ($refs.form.data.application.status == 'Draft' || $refs.form.data.application.status == 'Rejected')
          "
          custom-icon="fa fa-trash-alt"
          @click="cancel"
        >
          {{ $t('Front_Btn_Cancel') }}
        </Button>
        <Button
          type="info"
          v-if="$refs.form && $refs.form.data && $refs.form.data.applicationID"
          custom-icon="fa fa-history"
          @click="$refs.approvalHistoryTable.open({ processInstID: $refs.form.data.application.processInstID })"
        >
          {{ $t('Front_Btn_History') }}
        </Button>
      </template>
    </modal-form>
    <modal-form ref="showForm" v-if="page" :readonly="page.showViewCode == null" @on-after-save="$refs.table.loadData()">
      <template slot="footer">
        <span></span>
        <Button
          type="primary"
          v-if="
            $refs.showForm &&
            $refs.showForm.data &&
            $refs.showForm.data.application &&
            $refs.showForm.data.application.processInst &&
            $refs.showForm.data.application.processInst.isMessageEnable
          "
          custom-icon="fa fa-comment-dots"
          @click="openMessage()"
        >
          {{ $t('Front_Btn_Leave_Message') }}
        </Button>
        <Button type="info" custom-icon="fa fa-history" @click="$refs.approvalHistoryTable.open({ processInstID: $refs.showForm.data.application.processInstID })">
          {{ $t('Front_Btn_History') }}
        </Button>
      </template>
    </modal-form>
    <modal-table ref="approvalHistoryTable" view-code="ApprovalHistoryModal"></modal-table>
    <Modal v-model="messageOpened" scrollable>
      <div slot="header">
        <span class="title">{{ $t('Front_Label_Leave_Message') }}</span>
        <span class="description">{{ $t('Front_Label_Leave_Message_Desc') }}</span>
      </div>
      <div class="ivu-ml-8 ivu-mr-8">
        <Form ref="messageForm" :model="messageData" label-position="top" label-colon="：" class="ivu-mt" @submit.native.prevent>
          <Row :gutter="24" type="flex">
            <Col v-bind="grid24">
              <FormItem
                :label="$t('Front_Label_Message_Content')"
                key="message"
                prop="message"
                :rules="{
                  required: true,
                  message: this.$t('Front_Msg_Please_Input'),
                  trigger: 'blur,change'
                }"
              >
                <Input type="textarea" :rows="6" v-model="messageData.message" />
              </FormItem>
            </Col>
          </Row>
        </Form>
      </div>
      <template slot="footer">
        <Button type="primary" custom-icon="fa fa-check" @click="submitMessage">{{ $t('Front_Btn_Submit') }}</Button>
        <Button type="default" custom-icon="fa fa-times" @click="messageOpened = false">{{ $t('Front_Btn_Close') }}</Button>
      </template>
    </Modal>
  </div>
</template>
<script>
  import applicationApi from '../../api/application';
  import processInstApi from '../../api/processInst';
  import mixinPage from '../../mixins/page';
  import { mapActions } from 'vuex';

  export default {
    name: 'template-processPage',
    mixins: [mixinPage],
    components: {},
    data() {
      return {
        applicationType: {},
        page: {},
        messageData: {
          message: null
        },
        messageOpened: false
      };
    },
    computed: {},
    async created() {
      this.init(this.$route.meta.data.id);
    },
    watch: {
      $route() {
        this.init(this.$route.meta.data.id);
      }
    },
    methods: {
      ...mapActions('admin/viewPage', { loadPage: 'load' }),
      // 初始化
      async init(pageID) {
        let res = await this.loadPage(pageID);
        this.page = res.customPage;

        setTimeout(() => {
          this.$refs.table.init(this.page.tableViewCode, () => {
            this.$refs.table.loadData();
          });

          if (!!(this.page.formViewCode || '').trim()) {
            this.$refs.form.init(this.page.formViewCode);
          }

          if (!!(this.page.formViewCode || '').trim() || !!(this.page.showViewCode || '').trim()) {
            this.$refs.showForm.init(!(this.page.showViewCode || '').trim() ? this.page.formViewCode : this.page.showViewCode);
          }
        });
      },
      // 创建
      create() {
        let application = {
          status: 'Draft',
          applicantID: this.info.id,
          createTime: new Date()
        };

        this.$refs.form.openDefault({ application });
      },
      // 提交
      async submit() {
        let isOK = await this.$refs.form.validate();

        if (!isOK) {
          this.error('Front_Msg_Form_Validate_Fail');
        } else {
          let data = this.$refs.form.getFullData();

          if (!data) {
            // 表格验证失败
            return;
          }

          this.confirm('Front_Msg_Sure_To_Submit', async () => {
            await applicationApi.submit(this.page.applicationType, data);

            this.success('Front_Msg_Success', () => {
              this.$refs.table.loadData();
              this.$refs.form.close();
            });
          });
        }
      },
      // 保存
      async save() {
        let data = this.$refs.form.getFullData();

        if (!data) {
          // 表格验证失败
          return;
        }

        this.confirm('Front_Msg_Sure_To_Save', async () => {
          let res = await applicationApi.save(this.page.applicationType, data);

          this.success('Front_Msg_Success', () => {
            this.$refs.table.loadData();
            this.$refs.form.setData(res);
          });
        });
      },
      // 打开意见输入
      openMessage() {
        this.messageData.message = null;
        this.messageOpened = true;
      },
      // 提交意见
      async submitMessage() {
        let isOK = await this.$refs.messageForm.validate();

        if (!isOK) {
          this.error('Front_Msg_Form_Validate_Fail');
        } else {
          this.confirm('Front_Msg_Sure_To_Message_Application', async () => {
            await processInstApi.addMessage(this.$refs.showForm.data.application.processInstID, this.messageData.message);

            this.success('Front_Msg_Success', () => {
              this.messageData.message = null;
              this.messageOpened = false;
            });
          });
        }
      },
      // 撤销
      async cancel() {
        this.confirm('Front_Msg_Sure_To_Cancel_Application', async () => {
          await applicationApi.cancel(this.$refs.form.data.applicationID);

          this.success('Front_Msg_Success', () => {
            this.$refs.table.loadData();
            this.$refs.form.close();
          });
        });
      }
    }
  };
</script>
