<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" :return-columns="['application.status', 'application.applicantID']" :create-enable="allow('create')" @create="create">
        <template #top>
          <slot name="top"></slot>
        </template>
        <template #filter>
          <slot name="filter"></slot>
        </template>
        <template #customFilter>
          <slot name="customFilter"></slot>
        </template>
        <template #filterColumn="{ column, code }">
          <slot name="filterColumn" :column="column" :code="code"></slot>
        </template>
        <template #filterCommand>
          <slot name="filterCommand"></slot>
        </template>
        <template #middle>
          <slot name="middle"></slot>
        </template>
        <template #commandBefore="{ row, index }">
          <slot name="commandBefore" :row="row" :index="index"></slot>
        </template>
        <template #command="{ row, index }">
          <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="show(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="edit(row)"
          ></Button>
          <slot name="command" :row="row" :index="index"></slot>
        </template>
      </view-table>
    </Card>
    <modal-form ref="form" v-if="page" @on-after-save="$refs.table.loadData()">
      <template #top>
        <slot name="formTop"></slot>
      </template>
      <template #tableColumn="{ table, tableColumn, tableCode, row, index, column, code }">
        <slot name="formTableCommand" :table="table" :tableColumn="tableColumn" :tableCode="tableCode" :row="row" :index="row" :column="column" :code="code"></slot>
      </template>
      <template #tableCommand="{ table, tableColumn, tableCode, row, index }">
        <slot name="formTableCommand" :table="table" :tableColumn="tableColumn" :tableCode="tableCode" :row="row" :index="row"></slot>
      </template>
      <template #column="{ form, data, column, code }">
        <slot name="formColumn" :form="form" :data="data" :column="column" :code="code"></slot>
      </template>
      <template #bottom>
        <slot name="formBottom"></slot>
      </template>
      <template #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="
            isCancelable &&
            $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.application && $refs.form.data.application.processInstID"
          custom-icon="fa fa-route"
          @click="$refs.flowChart.open({ processInstID: $refs.form.data.application.processInstID })"
        >
          {{ $t('Front_Btn_Process') }}
        </Button>
        <Button
          type="info"
          v-if="$refs.form && $refs.form.data && $refs.form.data.application && $refs.form.data.application.processInstID"
          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 #top>
        <slot name="showFormTop"></slot>
      </template>
      <template #tableColumn="{ table, tableColumn, tableCode, row, index, column, code }">
        <slot name="showFormTableCommand" :table="table" :tableColumn="tableColumn" :tableCode="tableCode" :row="row" :index="row" :column="column" :code="code"></slot>
      </template>
      <template #tableCommand="{ table, tableColumn, tableCode, row, index }">
        <slot name="showFormTableCommand" :table="table" :tableColumn="tableColumn" :tableCode="tableCode" :row="row" :index="row"></slot>
      </template>
      <template #column="{ form, data, column, code }">
        <slot name="showFormColumn" :form="form" :data="data" :column="column" :code="code"></slot>
      </template>
      <template #bottom>
        <slot name="showFormBottom"></slot>
      </template>
      <template #footer>
        <span></span>
        <Button
          type="warning"
          v-if="
            isRecallable &&
            $refs.showForm &&
            $refs.showForm.data &&
            $refs.showForm.data.application &&
            $refs.showForm.data.applicationID &&
            $refs.showForm.data.application.status == 'Running'
          "
          custom-icon="fa fa-reply-all"
          @click="recall"
        >
          {{ $t('Front_Btn_Recall') }}
        </Button>
        <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()"
        >
          发表意见
        </Button>
        <Button
          type="info"
          v-if="$refs.showForm && $refs.showForm.data && $refs.showForm.data.application && $refs.showForm.data.application.processInstID"
          custom-icon="fa fa-route"
          @click="$refs.flowChart.open({ processInstID: $refs.showForm.data.application.processInstID })"
        >
          {{ $t('Front_Btn_Process') }}
        </Button>
        <Button
          type="info"
          v-if="$refs.showForm && $refs.showForm.data && $refs.showForm.data.application && $refs.showForm.data.application.processInstID"
          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>
      <template #header>
        <div>
          <span class="title">{{ $t('Front_Label_Leave_Message') }}</span>
          <span class="description">{{ $t('Front_Label_Leave_Message_Desc') }}</span>
        </div>
      </template>
      <div class="ivu-ml-8 ivu-mr-8">
        <Form ref="messageForm" :model="messageData" label-position="top" label-colon="：" class="ivu-mt" @submit.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 #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>
    <flow-chart ref="flowChart" />
  </div>
</template>
<script>
  import modelApi from '../../api/model';
  import customModelApi from '../../api/customModel';
  import applicationApi from '../../api/application';
  import processInstApi from '../../api/processInst';
  import mixinPage from '../../mixins/page';
  import flowChart from '../../components/workflow/flow-chart.vue';
  import { mapActions } from 'vuex';

  export default {
    // name: this.$route.name,
    mixins: [mixinPage],
    components: { flowChart },
    data() {
      return {
        filter: {},
        page: {},
        messageData: {
          message: null
        },
        messageOpened: false,
        isCancelable: false,
        isRecallable: false
      };
    },
    props: {
      // 表格视图
      tableViewCode: {
        type: String
      },
      // 表单视图
      formViewCode: {
        type: String
      },
      // 查看表单视图
      showViewCode: {
        type: String
      },
      // 申请类别
      applicationTypeCode: {
        type: String
      }
    },
    computed: {},
    async mounted() {
      if (this.$route.meta.data.id) {
        let res = await this.loadPage(this.$route.meta.data.id);
        this.page = res.customPage;

        this.init();
      } else if (this.applicationTypeCode) {
        let res = await modelApi.query('ApplicationType', { code: this.applicationTypeCode });

        if (res.data.length > 0) {
          this.page = {
            tableViewCode: this.tableViewCode,
            formViewCode: this.formViewCode,
            showViewCode: this.showViewCode,
            applicationType: res.data[0]
          };

          this.init();
        }
      }
    },
    // watch: {
    //   $route() {
    //     if (this.$route.meta.data.id) {
    //       //this.init(this.$route.meta.data.id);
    //     }
    //   }
    // },
    methods: {
      ...mapActions('admin/viewPage', { loadPage: 'load' }),
      // 初始化
      async init() {
        this.isCancelable = this.page.applicationType.isCancelable;
        this.isRecallable = this.page.applicationType.isRecallable;

        setTimeout(() => {
          // if (!this.allow('all')) {
          //   this.$refs.table.filterData['s_self'] = true;
          //   this.$refs.table.filterData['createUserID'] = this.info.id;
          // }

          this.$refs.table.init(this.page.tableViewCode, () => {
            if (!this.$refs.table.tableView.autoLoadDisable) {
              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();
          });
        });
      },
      // 撤回
      async recall() {
        this.confirm('Front_Msg_Sure_To_Recall_Application', async () => {
          await applicationApi.recall(this.$refs.showForm.data.applicationID);

          this.success('Front_Msg_Success', () => {
            this.$refs.table.loadData();
            this.$refs.showForm.close();
          });
        });
      },
      /**
       * 编辑项
       *
       * @param {object} row 行对象
       * @public
       */
      async edit(row) {
        let data = row;
        if (this.$refs.table.tableView.isCustom) {
          data = await customModelApi.get(this.$refs.table.tableView.model, row.id);
        } else if (!this.$refs.table.tableView.isDataSource) {
          data = await modelApi.get(this.$refs.table.tableView.model, row.id);
        }

        this.$refs.form.open(data);
      },
      /**
       * 查看项
       *
       * @param {object} row 行对象
       * @public
       */
      async show(row) {
        let data = row;
        if (this.$refs.table.tableView.isCustom) {
          data = await customModelApi.get(this.$refs.table.tableView.model, row.id);
        } else if (!this.$refs.table.tableView.isDataSource) {
          data = await modelApi.get(this.$refs.table.tableView.model, row.id);
        }

        this.$refs.showForm.open(data);
      }
    }
  };
</script>
