<template>
    <div class="app-container">
      <div class="header_main-placeholder">
        <div class="header_main">
          行级填报
          <div class="return_btn" @click="back"></div>
          <div class="add_btn" @click="save" v-if="(isAdd || isEdit) && editorData.templateId">保 存</div>
        </div>
      </div>

      <van-form ref="form" :class="{'form_readonly': disableEdit}">
        <van-row>
          <van-col :span="editorData.templateId ? 16 : 24">
            <field-select
              class="template-selector"
              :value="editorData.templateId"
              label=" 模板"
              value-key="reportName"
              data-key="id"
              placeholder="报表模板"
              :rules="[{ required: true }]"
              :readonly="true"
              :columns="templateList"
              @input="getTemplate"
            />
          </van-col>
          <van-col span="8" v-if="!!editorData.templateId">
            <field-date-picker
              class="field_no-label"
              v-model="editorData.reportYear"
              placeholder="报表年度"
              formatter="yyyy"
              :readonly="disableEdit"
              input-align="center"
              type="year"
            />
          </van-col>
        </van-row>
        <van-row v-if="!!editorData.templateId">
          <van-col span="8">
            <van-field class="field_no-label" :readonly="disableEdit" v-model="editorData.titleLeft" label="" placeholder="左上" input-align="left"/>
          </van-col>
          <van-col span="8">
            <van-field class="field_no-label" :readonly="disableEdit" v-model="editorData.titleCenter" label="" placeholder="中上" input-align="center"/>
          </van-col>
          <van-col span="8">
            <van-field class="field_no-label" :readonly="disableEdit" v-model="editorData.titleRight" label="" placeholder="右上" input-align="right"/>
          </van-col>
        </van-row>

        <div class="main-table" v-if="!!editorData.templateId">
            <div v-for="(header, rindex) in editorData.detailHeaders">
              <van-field v-if="header.type === '2'" label-width="50%" :readonly="disableEdit" v-model="editorData.rows[0][rindex].val" :label="header.headerName" :placeholder="header.headerName" input-align="right" type="number"/>
              <van-field v-else-if="header.type === '4'" label-width="50%" :readonly="disableEdit" v-model="editorData.rows[0][rindex].name" :label="header.headerName" :placeholder="header.headerName" input-align="right"/>
              <van-field v-else-if="header.type === '3'" label-width="50%" :readonly="disableEdit" v-model="editorData.rows[0][rindex].name" :label="header.headerName" :placeholder="header.headerName" type="digit" input-align="right"/>
              <van-field v-else label-width="50%" :readonly="true" :value="editorData.rows[0][rindex].name" :label="header.headerName" :placeholder="header.headerName" input-align="right"/>
            </div>
        </div>

        <template v-if="!!editorData.templateId">
          <div>
            <van-field :readonly="disableEdit" v-model="editorData.reportRemark" label="备注" placeholder="报表备注"/>
          </div>
<!--          <div>
            <van-field readonly :value="editorData.rule" label="规则" placeholder="报表效验公式"></van-field>
          </div>-->

          <van-row>
            <van-col span="8">
              <van-field class="field_no-label" :readonly="disableEdit" v-model="editorData.operatorDepartment" label="" placeholder="填报单位" input-align="left"/>
            </van-col>
            <van-col span="8">
              <van-field class="field_no-label" :readonly="disableEdit" v-model="editorData.operatorName" label="" placeholder="填报人" input-align="center"/>
            </van-col>
            <van-col span="8">
              <field-date-picker
                class="field_no-label"
                v-model="editorData.operatorDate"
                placeholder="填报日期"
                formatter="yyyy-MM-dd"
                :readonly="disableEdit"
                input-align="right"
              />
            </van-col>
          </van-row>
        </template>
      </van-form>
    </div>
</template>

<script>
import FieldSelect from "@/components/form/FieldSelect";
import {
  addReport, delReport,
  getReport,
  getReportTemplate,
  listReporttitle,
  updateReport
} from "@/api/sunVillage_info/entity/report";
import {array_grouping, array_toMap, date_format} from "@/utils";
import {Expression} from "@/utils/expression";
import {is_not_number} from "@/utils/utils";
import FieldDatePicker from "@/components/form/FieldDatePicker";
import {Notify} from "vant";
export default {
  name: "ReportLineView",
  components: {FieldDatePicker, FieldSelect},
  data() {
    return {
      editorData: {
        id: null,
        templateId: null,
        reportRemark: null,
        titleLeft: null,
        titleCenter: null,
        titleRight: null,
        reportStatus: "0",
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        reportName: '',
        operatorName: '',
        operatorDate: '',
        operatorDepartment: '',
        rule: null,
        reportYear: date_format('%Y'),
        headers: [],
        rows: [],
        cells: [],
        rules: [],
        headerRows: [],
        headerLength: 0,
        headerDeep: 0,
        headerTypes: [],
        header: null,
        detailHeaders: [],
      },
      templateList: [],
      loading: false,
      disableEdit: false,
      intent: 'add',
      templateId: null,
      reportId: null,
    };
  },
  created() {
    this.getTemplateList();
    this.parseQuery();
  },
  mounted(){
    this.init();
  },
  methods: {
    getTemplateList() {
      listReporttitle({
        type: '2',
        reportStatus: '0',
      }).then((resp) => {
        this.templateList = resp.rows;
      });
    },
    getTemplate() {
      if(!this.editorData.templateId && !this.editorData.id)
        return;
      this.loading = true;
      if(this.editorData.id) // 修改
      {
        getReport(this.editorData.id, {
          genDetailHeaders: true
        }).then((resp) => {
          let reportData = resp.data;
          getReportTemplate(reportData.templateId, {
            genDetailHeaders: true
          }).then((resp) => {
            let templateData = resp.data;
            this.setTableData(templateData, reportData);
          }).finally(() => {
            this.loading = false;
          });
        }).catch(() => {
          this.loading = false;
        });
      }
      else
      {
        getReportTemplate(this.editorData.templateId, {
          genDetailHeaders: true
        }).then((resp) => {
          let templateData = resp.data;
          this.setTableData(templateData);
        }).finally(() => {
          this.loading = false;
        });
      }
    },
    setTableData(templateData, reportData) {
      let data;
      if(!reportData)
      {
        data = templateData;
        data.rows.forEach((x) => {
          x.forEach((y) => {
            y.error = false;
          });
        });
      }
      else
      {
        let cells = reportData.cells;
        data = reportData;
        data.headers = templateData.headers;
        data.headerRows = templateData.headerRows;
        data.headerTypes = templateData.headerTypes;
        data.headerLength = templateData.headerLength;
        data.headerDeep = templateData.headerDeep;
        data.detailHeaders = templateData.detailHeaders;
        data.rows = templateData.rows;
        data.cells = templateData.cells;
        data.rules = templateData.rules;
        data.rule = templateData.rule;

        let group = array_grouping(cells, (x) => x.rowIndex);
        Object.keys(group).forEach((x) => group[x] = array_toMap(group[x], (x) => x.colIndex));
        data.rows.forEach((cols, rowIndex) => {
          cols.forEach((x) => {
            if(group[rowIndex] && group[rowIndex][x.colIndex])
            {
              if(templateData.headerTypes[x.colIndex] === '4')
                x.name = group[rowIndex][x.colIndex].name;
              x.val = group[rowIndex][x.colIndex].val;
            }
          })
        });
      }
      this.editorData = data;
    },
    calcAlign(type) {
      switch(type)
      {
        case '2':
          return 'right';
        case '3':
        case '4':
          return 'center';
        case '1':
          return 'left';
      }
    },
    calcColor(type) {
      switch(type)
      {
        case '2':
          return 'unset';
        case '4':
          return 'unset';
        case '3':
          return '#d7e8f3';
        case '1':
          return '#aad8f6';
      }
    },
    calcTextColor(type) {
      switch(type)
      {
        case '2':
        case '4':
          return '#2facfe';
        case '3':
        case '1':
          return '#858585';
      }
    },
    save() {
      this.$refs.form.validate().then(() => {
        this.preHandle();
        this.loading = true;
        let func = this.editorData.id ? updateReport : addReport;
        func(this.editorData).then((resp) => {
          this.notify("保存成功!", 'success');
          this.back();
        }).finally(() => {
          this.loading = false;
        });
      }).catch(() => {
        this.notify("请填写完整表单", 'danger');
        this.$refs.form.scrollToField();
      });
    },
    preHandle() {
      this.editorData.cells = [];
      this.editorData.rows.forEach((x) => this.editorData.cells.push(...x));
    },
    reset() {
      this.$refs.form.resetValidation();
      this.editorData = {
        id: null,
        deptId: null,
        deptName: null,
        templateId: null,
        reportName: null,
        reportYear: null,
        reportRemark: null,
        titleLeft: null,
        titleCenter: null,
        titleRight: null,
        rule: null,
        operatorName: null,
        operatorDate: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        headers: [],
        rows: [],
        cells: [],
        rules: [],
        headerRows: [],
        headerLength: 0,
        headerDeep: 0,
        headerTypes: [],
        header: null,
        detailHeaders: [],
      };
    },
    parseQuery() {
      let query = this.$route.query;
      this.templateId = query.templateId;
      this.reportId = query.reportId;
      this.intent = query.intent;
      if(!this.reportId)
      {
        this.intent = 'add';
        return;
      }
      if(this.intent === 'add')
      {
        this.reportId = null;
      }
      if(!this.templateId && !this.reportId)
      {
        this.$router.back();
        return;
      }
    },
    init() {
      this.editorData.templateId = this.templateId;
      this.editorData.id = this.reportId;
      this.getTemplate();
      this.disableEdit = this.intent === 'view';
    },
    back() {
      this.$router.back();
    },
    notify(message, type) {
      Notify.clear();
      Notify({ type: type || 'primary', message: message });
    },
  },
  computed: {
    isAdd() {
      return this.intent === 'add';
    },
    isEdit() {
      return this.intent === 'edit';
    },
    isView() {
      return this.intent === 'view';
    },
  }
}
</script>

<style scoped lang="scss">
.app-container{
   background: #e9e9e9;
   min-height: 100vh;
   width: 100vw;
  .header_main-placeholder {
    height: 116px;
  }

  .header_main {
    height: 116px;
    background: url('../../../assets/images/sunVillage_info/list_head.png') no-repeat;
    background-size: 100% 100%;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    font-size: 36px;
    line-height: 116px;
    text-align: center;
    color: #fff;
    z-index: 999;

    .return_btn {
      width: 24px;
      height: 43.2px;
      background: url('../../../assets/images/sunVillage_info/list_icon_5.png') center center no-repeat;
      background-size: 20px 36px;
      position: absolute;
      left: 38px;
      top: 36px;
    }

    .add_btn {
      width: 72px;
      //height: 40.8px;
      //background: url('../../../assets/images/sunVillage_info/list_icon_9.png') center center no-repeat;
      //background-size: 47px 34px;
      position: absolute;
      right: 38px;
      top: 0;
      font-size: 28px;
    }
  }

  .main-table {
    overflow-x: auto;
    overflow-y: auto;
    position: relative;
    background-color: #ffffff;
    padding: 0.15rem 0.15rem;
    border-radius: 0.15rem;
    margin: 0.1rem 0.1rem;

    table {
      width: max-content;
      border-collapse: collapse;
      border: 0.01rem solid #1989fa;
      table-layout: fixed;
    }
    thead td {
      text-align: center;
      border: 0.01rem solid #1989fa;
      height: 1rem;
      font-size: 0.32rem;
      padding: 0 0.4rem;
      margin: 0;
      font-weight: bold;
      max-width: 1.2rem;
    }
    tbody td {
      font-size: 0.3rem;
      border: 0.01rem solid #1989fa;
      height: 1rem;
      white-space: break-spaces;
      word-wrap: break-word;
      overflow-wrap: break-word;
      padding: 0;
      margin: 0;
      max-width: 1.5rem;
      position: relative;
    }

    .input-field {
      width: 100%;
      background-color: unset;
      border: 0;
    }

    .validate-error {
      color: #F56C6C;
    }
    .validate-error-box {
      color: #F56C6C;
      border: 0.02rem solid #F56C6C;
    }
  }
  .align-right {
    text-align: right;
  }
  .align-center {
    text-align: center;
  }
  .full-height {
    height: 100%;
  }

  /deep/ .van-field__label {
    background-color: #2facfe;
    margin: 0;
    color: #fff;
    border-top-left-radius: 0.15rem;
    border-bottom-left-radius: 0.15rem;
    padding: 0 0.2rem;
    display: flex;
    align-items: center;
  }

  /deep/ .van-field__body {
    background-color: #ffffff;
    border-top-right-radius: 0.15rem;
    border-bottom-right-radius: 0.15rem;
    padding: 0 0.1rem;
  }

  /deep/ .van-field__body {
    height: 100%;
  }

  /deep/ .van-field {
    background-color: unset;
    padding: 0.1rem 0.15rem;
    height: 1rem;
  }

  .field_no-label /deep/ .van-field__body {
    border-top-left-radius: 0.15rem;
    border-bottom-left-radius: 0.15rem;
  }

  .main-table /deep/ .van-field__body {
    border-right: 0.01rem solid #ccc;
    border-top: 0.01rem solid #ccc;
    border-bottom: 0.01rem solid #ccc;
  }

  .template-selector /deep/ span {
    padding-left: 0.8rem;
    background: #2facfe url('../../../assets/images/sunVillage_info/list_icon_11.png') left center no-repeat;
    background-size: 0.45rem;
  }

  .form_readonly /deep/ .van-icon-arrow-down {
    display: none;
  }

  .main-table /deep/ .van-field {
    height: unset;
    min-height: 1rem;
  }
}


</style>
