<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"
        view-code="ApplicationType"
        :select-enable="true"
        :create-enable="allow('create')"
        :remove-enable="allow('remove')"
        @create="$refs.form.open()"
        @edit="({ row }) => edit(row)"
      >
        <template #filterCommand>
          <Button v-if="allow('export')" size="small" type="info" custom-icon="fa fa-cloud-download-alt" @click="exportFile()">{{ $t('Front_Btn_Export') }}</Button>
          <file-upload v-if="allow('import')" url="api/ApplicationType/importFile" accept=".appt" @on-success="importFileSuccess">
            <template #>
              <Button type="primary" custom-icon="fa fa-cloud-upload-alt" size="small">{{ $t('Front_Btn_Import') }}</Button>
            </template>
          </file-upload>
        </template>
        <template #command="{ row }">
          <Button
            v-if="allow('notivicationSetting')"
            size="small"
            :title="$t('Front_Btn_NotificationSetting')"
            type="primary"
            custom-icon="fa fa-mail-bulk"
            @click="notificationSetting(row)"
          ></Button>
        </template>
      </view-table>
    </Card>
    <modal-form
      ref="form"
      view-code="ApplicationTypeEdit"
      :create-enable="allow('create')"
      :edit-enable="allow('edit')"
      @on-after-save="$refs.table.loadData()"
      @on-change="formChange"
    >
      <template #column="{ code }">
        <div v-if="code == 'titleColumn'">
          <Input type="text" :readonly="true" v-model="$refs.form.data.titleColumn" @on-focus="openTitleColumnSelect()">
            <template #prepend>
              <Button custom-icon="fa fa-search" @click="openTitleColumnSelect()"></Button>
            </template>
          </Input>
        </div>
      </template>
      <template #bottom>
        <Divider :plain="true" dashed orientation="left" size="small">
          <span class="title">{{ $t('Front_Label_Process_Property_Mapping') }}</span>
        </Divider>
        <view-table ref="propertyTable" view-code="ApplicationProcessProperty" :static="true">
          <template #column="{ row, code }">
            <template v-if="code == 'column'">
              <Input type="text" size="small" :readonly="true" v-model="row.column" @on-focus="openPropertyColumnSelect(row)">
                <template #prepend>
                  <Button size="small" custom-icon="fa fa-search" @click="openPropertyColumnSelect(row)"></Button>
                </template>
              </Input>
            </template>
          </template>
        </view-table>
      </template>
      <template #footer>
        <Button type="primary" custom-icon="fa fa-save" @click="save">{{ $t('Front_Btn_Save') }}</Button>
      </template>
    </modal-form>
    <modal-form ref="notificationSettingForm" view-code="ApplicationNotificationSetting">
      <template #footer>
        <Button type="primary" custom-icon="fa fa-save" @click="saveSetting">{{ $t('Front_Btn_Save') }}</Button>
      </template>
    </modal-form>
    <column-check ref="columnCheck" />
  </div>
</template>
<script>
  import columnCheck from '../../components/view/column-check.vue';
  import mixinPage from '../../mixins/page';
  import applicationTypeApi from '../../api/applicationType';
  import modelApi from '../../api/model';

  export default {
    name: 'system-applicationType',
    mixins: [mixinPage],
    components: { columnCheck },
    data() {
      return {
        applicationType: null,
        processProperties: []
      };
    },
    computed: {},
    created() {},
    methods: {
      // 打开标题字段选择界面
      openTitleColumnSelect() {
        if (this.$refs.form.data.model == null) {
          return;
        }

        this.$refs.columnCheck.open(this.$refs.form.data.model, checked => {
          this.$refs.form.data.titleColumn = checked.code;
          //this.$forceUpdate();
        });
      },
      // 打开属性字段选择界面
      openPropertyColumnSelect(row) {
        if (this.$refs.form.data.model == null) {
          return;
        }

        this.$refs.columnCheck.open(this.$refs.form.data.model, checked => {
          row.column = checked.code;
          //this.$forceUpdate();
        });
      },
      // 编辑
      edit(row) {
        this.$refs.form.open(row);
        this.initPropertyData();
      },
      // 保存
      async save() {
        let isOK = await this.$refs.form.validate();

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

            // if (!(data.formViewCode || '').trim() && !(data.routerPath || '').trim()) {
            //   this.error('Front_Msg_Form_View_Router_Path_Required');
            //   return;
            // }

            data.processProperty = JSON.stringify(this.$refs.propertyTable.data);

            if (!data.id) {
              await modelApi.add('ApplicationType', data);
            } else {
              await modelApi.update('ApplicationType', data);
            }

            this.success('Front_Msg_Success', () => {
              this.$refs.form.close();
              this.$refs.table.loadData();
            });
          });
        }
      },
      // 模型变化
      async formChange(sender) {
        let data = this.$refs.form.data;
        if (sender && sender.code == 'processID') {
          data.processProperty = null;
          this.initPropertyData();
        } else if (sender && sender.code == 'model') {
          data.titleColumn = null;
          data.formViewCode = null;
          data.processProperty = null;
          this.initPropertyData();
        }

        // if (sender && sender.code == 'formViewCode') {
        //   data.model = selected.model;
        //   data.processProperty = null;
        //   data.titleColumn = null;
        //   this.initPropertyData();
        // }

        // let columnRouterPath = this.$refs.form.columns.find(item => {
        //     return item.code == 'routerPath';
        // });
        // let columnFormViewID = this.$refs.form.columns.find(item => {
        //     return item.code == 'formViewID';
        // });

        // if (data.isRedirect) {
        //     columnRouterPath.isShow = true;
        //     columnFormViewID.isShow = false;
        // } else {
        //     columnRouterPath.isShow = false;
        //     columnFormViewID.isShow = true;
        // }
      },
      // 初始化申请流程参数数据
      async initPropertyData() {
        let processID = this.$refs.form.data.processID;
        let processProperty = this.$refs.form.data.processProperty;
        this.processProperties = [];

        if (processID != null) {
          let res = await modelApi.query('ProcessProperty', { processID });

          let processProperties = res.data;
          let existProperties = [];

          if (processProperty != null) {
            existProperties = JSON.parse(processProperty);
          }

          this.processProperties = processProperties.map(processProperty => {
            let existProperty = existProperties.find(item => item.propertyCode == processProperty.propertyCode);

            return {
              propertyCode: processProperty.propertyCode,
              propertyName: processProperty.propertyName,
              column: existProperty == null ? null : existProperty.column
            };
          });
        }

        this.$refs.propertyTable.loadData(this.processProperties);
      },
      // 通知设置
      notificationSetting(row) {
        this.applicationType = row;
        let setting = {};
        if (!!(row.notificationSetting || '').trim()) {
          setting = JSON.parse(row.notificationSetting);
        }

        this.$refs.notificationSettingForm.open(setting);
      },
      // 保存通知设置
      async saveSetting() {
        let isOK = await this.$refs.notificationSettingForm.validate();

        if (!isOK) {
          this.error('Front_Msg_Form_Validate_Fail');
        } else {
          this.confirm('Front_Msg_Sure_To_Save', async () => {
            let data = this.$refs.notificationSettingForm.getFullData();

            this.applicationType.notificationSetting = JSON.stringify(data);

            await modelApi.update('ApplicationType', this.applicationType);
            this.success('Front_Msg_Success', () => {
              this.$refs.notificationSettingForm.close();
              this.$refs.table.loadData();
            });
          });
        }
      },
      // 导出文件
      exportFile() {
        let ids = this.$refs.table.getSelected().map(x => {
          return x.id;
        });
        if (ids.length > 0) {
          applicationTypeApi.exportFile(ids);
        } else {
          this.error('Front_Msg_Please_Select_Export_Item');
        }
      },
      // 导入成功
      importFileSuccess(res) {
        if (res.code == 0) {
          this.success('Front_Msg_Success', () => {
            this.$refs.table.loadData();
          });
        } else {
          this.error(res.message);
        }
      }
    }
  };
</script>
