<template>
  <div class="yo-form-page">
    <a-spin :spinning="loading" class="w-100-p h-100-p" tip="表单加载中..." v-if="loading">
      <a-icon slot="indicator" spin type="loading" />
      <div title="用于撑高spin"></div>
    </a-spin>
    <div class="yo-form-page-layout" v-else>
      <!-- 底部工具栏(需放在前面) -->
      <div class="yo-form-page--bar yo-form-page--bar--with-tab">
        <container>
          <div class="yo-form-page--bar-inner">
            <span>
              <!-- 可以在工具栏中增加其他控件(只能在一行内) -->
              <a-form-model
                :label-col="labelCol"
                :model="form"
                :rules="rules"
                :wrapper-col="wrapperCol"
                layout="inline"
                ref="form"
                v-if="param.record.patrolInfo.status == 3"
              >
                <a-form-model-item class="ant-row-flex" label="审核意见" prop="taskCheckRecord.content">
                  <a-textarea
                    auto-size
                    class="w-500"
                    placeholder="请输入审核意见"
                    v-model="form.taskCheckRecord.content"
                  />
                </a-form-model-item>
                <a-form-model-item>
                  <a-button @click="onCheck(6)" type="primary">通过</a-button>
                  <a-button @click="onCheck(-1)" type="primary">退回</a-button>
                </a-form-model-item>
              </a-form-model>
              <!-- ... -->
            </span>
            <span>
              <a-button
                @click="onSubmit('houseInfoSave')"
                type="primary"
                v-if="param.record.patrolInfo.status >=-1 && param.record.patrolInfo.status <3"
              >保存</a-button>
              <a-button
                @click="onSubmitToCheck"
                type="primary"
                v-if="param.record.patrolInfo.status == 2"
              >提交审核</a-button>
              <a-button @click="closeContentWindow()">取消</a-button>
            </span>
          </div>
        </container>
      </div>

      <div :style="{ paddingBottom: 0 }" class="yo-form-page--header">
        <container>
          <a-descriptions :column="4" title>
            <a-descriptions-item label="区县（市）">{{param.record.houseCode.areaName}}</a-descriptions-item>
            <a-descriptions-item label="街道（乡镇）">{{param.record.houseCode.roadName}}</a-descriptions-item>
            <a-descriptions-item label="社区">{{param.record.houseCode.commName}}</a-descriptions-item>
            <a-descriptions-item label="片区">{{param.record.houseCode.zoneName}}</a-descriptions-item>
            <a-descriptions-item
              :span="2"
              label="编号"
            >{{`${param.record.houseCode.areaName}-${param.record.houseCode.roadName}-${param.record.houseCode.commName}-${param.record.houseCode.projectFullName}-${`000${param.record.houseCode.no}`.slice(-3)}`}}</a-descriptions-item>
            <a-descriptions-item :span="2" label="编码">{{param.record.houseCode.houseCode}}</a-descriptions-item>
          </a-descriptions>
        </container>
      </div>

      <!-- 表单主体 -->
      <!-- 
      挂载了一个content到tab后面
      如果直接使用antd-vue的tab,将会莫名其妙地做各种多余的渲染,导致卡顿
      现在只使用其tab卡片,重写了一个tab内容
      -->
      <div class="yo-tab-external-mount">
        <a-tabs @change="onTabChange">
          <template v-for="(tab, index) in tabs">
            <a-tab-pane :force-render="true" :key="index" :tab="tab.title" v-if="tab.show"></a-tab-pane>
          </template>
        </a-tabs>
        <div class="yo-tab-external-mount-content" v-if="!loading">
          <template v-for="(tab, index) in tabs">
            <div
              :class="tab.active ? 'yo-tab-external-tabpane-active' : 'yo-tab-external-tabpane-inactive'"
              :key="index"
              class="yo-tab-external-tabpane"
              v-if="tab.show"
            >
              <component
                :frame="self"
                :id="id"
                :is="tab.component"
                :param="param"
                ref="forms"
                v-if="tab.component"
              />
            </div>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  props: ['id', 'param'],

  data() {
    return {
      labelCol: { flex: '150px' },
      wrapperCol: { flex: '1' },
      form: {
        taskCheckRecord: {
          content: '',
        },
      },
      rules: {
        /* ... */
        'taskCheckRecord.content': [{ required: true, message: '审核意见不能为空' }],
      },

      saving: false,
      loading: true,

      tabs: [
        {
          title: '房屋基本情况',
          component: () => import('./base'),
          active: true,
          show: true,
        },
        {
          title: '幕墙信息',
          name: 'curtainWall',
          component: () => import('./curtainWall'),
          active: false,
          show: false,
        },
        {
          title: '面砖信息',
          name: 'faceBrick',
          component: () => import('./faceBrick'),
          active: false,
          show: false,
        },
        {
          title: '墙面粉刷信息',
          name: 'whiteWash',
          component: () => import('./whiteWash'),
          active: false,
          show: false,
        },
        {
          title: '墙面涂料信息',
          name: 'coating',
          component: () => import('./coating'),
          active: false,
          show: false,
        },
        {
          title: '巡查登记',
          name: 'patrol',
          component: () => import('./patrol'),
          active: false,
          show: true,
        },
      ],
    };
  },

  computed: {
    self() {
      return this;
    },
  },

  created() {
    this.$api.houseInfoGetByTaskId({ taskId: this.param.taskId }).then(({ data }) => {
      this.$set(this.param, 'record', data);
      this.loading = false;
    });
  },

  methods: {
    onCheck(result) {
      this.$refs.form.validate((valid, err) => {
        if (valid) {
          var checkRecord = {
            taskCheckRecord: {
              taskId: this.param.taskId,
              passOrBack: +result,
              content: this.form.taskCheckRecord.content,
            },
          };
          this.onSubmit('houseInfoSave', checkRecord);
          /** 验证通过后可以对数据进行转换得到想要提交的格式 */
          /* ... */
        } else {
          console.log(err);
        }
      });
    },
    async onSubmit(api, append) {
      let formData = {},
        flag = true;
      for (let i = 0; i < this.$refs.forms.length; i++) {
        const form = this.$refs.forms[i];
        try {
          const data = await form.onGetData();
          formData = {
            ...formData,
            ...data,
          };
        } catch (e) {
          if (e) {
            Object.keys(e).forEach((p) => {
              this.$message.error(e[p][0].message);
            });
          }
          flag = false;
        }
      }

      if (!flag) {
        return;
      }

      if (append) {
        formData = {
          ...formData,
          ...append,
        };
      }

      /**
       * 对表单提交进行处理
       */
      if (formData.houseCode) {
        formData.houseCode.id = this.param.record.houseCode.id;
      }

      if (formData.patrolInfo && this.param.taskId) {
        formData.patrolInfo.id = this.param.taskId;
      }

      this.saving = true;

      this.$api[api](formData).finally(() => {
        this.saving = false;
      });
    },
    onSubmitToCheck() {
      this.onSubmit('houseInfoSubmitToCheck');
    },
    onTabChange(key) {
      this.tabs.forEach((p, i) => {
        p.active = i === key;
      });
    },

    onTogglePane(show, name) {
      const pane = this.tabs.find((p) => p.name === name);
      if (pane) {
        pane.show = show;
      }
    },
  },
};
</script>