<template>
  <div>
    <div class="customer-head">
      <div class="customer-back">
        <el-button type="danger" style="border: none;background: none;color: red" icon="el-icon-arrow-left"
                   @click="backToList(0)">返回列表
        </el-button>
        <el-button v-if="detailData.id" type="danger" style="border: none;background: none;color: red"
                   icon="el-icon-arrow-left"
                   @click="backToList(1)">返回审核列表
        </el-button>
      </div>
      <div class="add-customer-btn">
        <el-button class="el-button--small-yh" type="primary" size="small" :disabled="form.status>0"
                   @click="editCustomer">保存数据
        </el-button>
      </div>
    </div>
    <trade-card title="基础资料" style="margin-top: 50px">
      <avue-form :option="optionForm" v-model="form" ref="form">
      </avue-form>
    </trade-card>
    <trade-card title="明细信息">
      <avue-crud
          :option="option"
          :data="dataList"
          v-model="formTwo"
          ref="crud"
          :key="key"
          :before-open="beforeOpen"
          @row-save="rowSave"
          @row-update="rowUpdate"
          @resetColumn="resetColumnTwo('crud','option','optionBack',257.1)"
          @saveColumn="saveColumnTwo('crud','option','optionBack',257.1)">
        <template slot="corpNameForm" slot-scope="scope">
          <crop-select v-model="formTwo.corpId" corpType="KH"
                       @getCorpData="(row)=>{getGSData(row,['formTwo','corpName'])}"/>
        </template>
        <template slot="monthForm" slot-scope="scope">
          <el-input-number v-model="formTwo.month" :min="1" :max="12" placeholder="请输入 月" :controls="false"
                           style="width: 100%;"></el-input-number>
        </template>
        <template slot-scope="{type,size,row,index,disabled}" slot="menu">
          <el-button icon="el-icon-edit" :size="size" :disabled="disabled" :type="type"
                     @click="$refs.crud.rowEdit(row,index)">编辑
          </el-button>
          <el-button icon="el-icon-delete" :size="size" :disabled="disabled" :type="type"
                     @click="rowDel(row,index,'MX')">删除
          </el-button>
        </template>
        <template slot="menuLeft" slot-scope="scope">
          <el-button class="el-icon-download" type="info" size="small" :disabled="!form.id" @click="openReport">
            报表打印
          </el-button>
        </template>
      </avue-crud>
    </trade-card>
    <!--    报表-->
    <report-dialog
        :switchDialog="switchDialog"
        :reportId="form.id"
        reportName="预算分析"
        @onClose="onClose()"
    />
  </div>
</template>

<script>
import {
  detail,
  submit,
  tradingBoxItem,
} from "@/api/annualBudget.js";
import reportDialog from "@/components/report-dialog/main.vue";

export default {
  name: "detailsPage",
  props: {
    onLoad: Object,
    detailData: Object
  },
  components: {
    reportDialog
  },
  data() {
    return {
      key: 0,
      switchDialog: false,
      form: {},
      formTwo: {},
      optionForm: {
        menuBtn: false,
        span: 6,
        column: [{
          label: '标题',
          prop: 'title',
          rules: [{
            required: true,
            message: " ",
            trigger: "blur"
          }]
        }, {
          label: "年份",
          prop: "particularYear",
          type: "year",
          dataType: 'string',
          valueFormat: "yyyy",
          width: 100,
          rules: [{
            required: true,
            message: " ",
            trigger: "blur"
          }]
        }]
      },
      option: {},
      optionBack: {
        align: 'center',
        index: true,
        selection: false,
        addBtnText: "录入明细",
        refreshBtn: false,
        addBtn: true,
        span: 8,
        addRowBtn: false,
        cellBtn: false,
        editBtn: false,
        height: 600,
        delBtn: false,
        menuWidth: 200,
        dialogTop: 25,
        dialogWidth: "80%",
        summaryText: "合计",
        showSummary: true,
        sumColumnList: [{
          name: "keter",
          type: "sum",
          decimals: 2
        }, {
          name: "drivemaster",
          type: "sum",
          decimals: 2
        }, {
          name: "luxxan",
          type: "sum",
          decimals: 2
        }, {
          name: "xcentway",
          type: "sum",
          decimals: 2
        }],
        column: [{
          label: "年份",
          prop: "year",
          type: "year",
          overHidden: true,
          valueFormat: "yyyy",
          width: 100,
          rules: [{
            required: true,
            message: " ",
            trigger: "blur"
          }]
        }, {
          label: "月",
          prop: "month",
          width: 100,
          controls: false,
          type: 'number',
          rules: [{
            required: true,
            message: " ",
            trigger: "blur"
          }]
        }, {
          label: "客户名称",
          prop: "corpName",
          overHidden: true,
          width: 100,
          rules: [{
            required: true,
            message: " ",
            trigger: "blur"
          }]
        }, {
          label: "欧记",
          prop: "keter",
          overHidden: true,
          type: 'number',
          value: 0,
          precision: 2,
          controls: false,
          width: 100,
        }, {
          label: "登马",
          prop: "drivemaster",
          overHidden: true,
          type: 'number',
          value: 0,
          precision: 2,
          controls: false,
          width: 100,
        }, {
          label: "路迈",
          prop: "luxxan",
          overHidden: true,
          type: 'number',
          value: 0,
          precision: 2,
          controls: false,
          width: 100,
        }, {
          label: "爱特路",
          prop: "xcentway",
          type: 'number',
          value: 0,
          precision: 2,
          controls: false,
          overHidden: true,
          width: 100,
        }, {
          label: "汇总",
          prop: "quantitySummary",
          type: 'number',
          value: 0,
          precision: 2,
          display: false,
          controls: false,
          overHidden: true,
          width: 100,
        }]
      },
      dataList: [],
      disabled: false,
    }
  },
  async created() {
    this.option = await this.getColumnData(this.getColumnName(257.1), this.optionBack);
    if (this.onLoad.id) {
      this.refresh(this.onLoad.id, true)
    }
    this.findObject(this.option.column, "keter").change =
        this.findObject(this.option.column, "drivemaster").change =
            this.findObject(this.option.column, "luxxan").change =
                this.findObject(this.option.column, "xcentway").change = (data) => {
                  this.formTwo[data.column.prop] = data.value
                  this.formTwo.quantitySummary = this.formTwo.keter + this.formTwo.drivemaster + this.formTwo.luxxan + this.formTwo.xcentway
                }
    this.key++
  },
  methods: {
    getGSData(row, type) {
      this[type[0]][type[1]] = row.cname
    },
    // 报表
    openReport() {
      this.switchDialog = !this.switchDialog;
    },
    // 报表关闭
    onClose(val) {
      this.switchDialog = val;
    },
    // 明细删除
    rowDel(row, index, type) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
            if (row.id) {
              tradingBoxItem(row.id).then(res => {
                if (res.data.success) {
                  this.$message.success("操作成功!");
                  this.dataList.splice(index, 1);
                }
              });
            } else {
              this.dataList.splice(index, 1);
              this.$message.success("操作成功!");
            }
          }
      );
    },
    refresh(id, type) {
      const loading = this.$loading({
        lock: true,
        text: '加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(255,255,255,0.7)'
      });
      detail({id: id}).then(res => {
        this.form = res.data.data
        this.dataList = res.data.data.itemList
        loading.close();
        this.key++
      })
    },
    //新增修改
    editCustomer() {
      this.$refs["form"].validate((valid, done) => {
        done()
        if (valid) {
          let data = {
            ...this.form,
            itemList: this.dataList,
          }
          const loading = this.$loading({
            lock: true,
            text: '加载中',
            spinner: 'el-icon-loading',
            background: 'rgba(255,255,255,0.7)'
          });
          submit(data).then(res => {
            if (this.form.id) {
              this.$message.success("修改成功")
            } else {
              this.$message.success("新增成功")
            }
            loading.close();
            this.refresh(res.data.data.id)
          }).catch(() => {
            loading.close();
          })
        }
      });
    },
    rowSave(form, done, loading) {
      done(form)
    },
    rowUpdate(form, index, done, loading) {
      done(form)
    },
    beforeOpen(done, type) {
      if (!['view', 'edit'].includes(type)) {
        this.formTwo.year = this.form.particularYear
      }
      done();
    },
    backToList(type) {
      if (type == 0) {
        if (this.detailData.id) {
          this.$router.push({
            path: '/boxManagement/exportShipment/index'
          });
        }
        this.$emit("backToList", type);
      } else if (type == 1) {
        this.$router.push({
          path: '/approveData/index'
        });
        this.$emit("backToList", type);
      }
    },
    //自定义列保存
    async saveColumnTwo(ref, option, optionBack, code) {
      /**
       * 已定义全局方法，直接使用，saveColumnData保存列数据方法,参数传值(表格名称，当前表格的option数据)
       * 已定义全局方法，直接使用，getColumnName方法用来获取枚举值，参数根据自己定义的code值获取中文名
       * 一定要执行异步操作，要等接口成功返回，才能执行下一行代码
       */
      const inSave = await this.saveColumnData(this.getColumnName(code), this[option]);
      if (inSave) {
        this.$message.success("保存成功");
        //关闭窗口
        this.$refs[ref].$refs.dialogColumn.columnBox = false;
      }
    },
    //自定义列重置
    async resetColumnTwo(ref, option, optionBack, code) {
      this[option] = this[optionBack];
      const inSave = await this.delColumnData(this.getColumnName(code), this[optionBack]);
      if (inSave) {
        this.$message.success("重置成功");
        this.$refs[ref].$refs.dialogColumn.columnBox = false;
        this.findObject(this.option.column, "keter").change = this.findObject(this.option.column, "drivemaster").change = this.findObject(this.option.column, "luxxan").change = this.findObject(this.option.column, "xcentway").change = (data) => {
          this.formTwo[data.column.prop] = data.value
          this.formTwo.quantitySummary = this.formTwo.keter + this.formTwo.drivemaster + this.formTwo.luxxan + this.formTwo.xcentway
        }
      }
    }
  }
}
</script>

<style scoped>
::v-deep .el-form-item {
  margin-bottom: 8px;
}
</style>
