<template>
  <div class="flex flex-justify-start flex-align-center flex-col">
    <div class="flex flex-center full-width flex-justify-between mt-10 mb-10">
      <span class="full-width text-left bold">{{ info.dictValue }}</span>
      <el-button
        v-if="detail.can_update"
        type="primary"
        @click="disabled = !disabled"
      >
        {{ disabled ? '编 辑' : '保 存' }}
      </el-button>
    </div>
    <div class="mt-10 mb-10 full-width" style="width: 93%">
      <base-button
        v-if="detail.can_update"
        title="新增年度"
        icon="Plus"
        @click="addYear(1)"
      />
    </div>
    <div class="mt-10" style="width: 90%">
      <el-form
        :model="form"
        label-width="180px"
        :disabled="disabled"
        label-position="left"
        class="form-content flex flex-col"
      >
        <el-form-item
          v-for="(item, index) in completeCount"
          :key="item"
          label-width="0"
        >
          <div class="flex flex-col flex-center full-width">
            <div class="flex flex-center flex-justify-between full-width">
              <div class="flex-child-average full-width flex flex-center">
                <span style="width: 320px"
                  >{{
                    form.month_plan_complete_amount[index]
                      ? form.month_plan_complete_amount[index].year
                      : ''
                  }}年度计划投资（万元）</span
                >
                <div class="disable-input" @change="change(item)">
                  {{
                    form.month_plan_complete_amount[index]
                      ? form.month_plan_complete_amount[index].sum
                      : ''
                  }}
                </div>
              </div>
              <div style="width: 20px"></div>
              <div class="flex-child-average full-width flex flex-center">
                <span style="width: 380px"
                  >{{
                    form.month_plan_complete_amount[index]
                      ? form.month_plan_complete_amount[index].year
                      : ''
                  }}年度累计投资（万元）</span
                >
                <div class="disable-input" @change="change(item)">
                  {{
                    form.month_complete_amount[index]
                      ? form.month_complete_amount[index].sum
                      : ''
                  }}
                </div>
                <div
                  class="btnSub pointer"
                  @click="
                    showMonth(form.month_complete_amount[index].year, 1, index)
                  "
                >
                  月填报
                </div>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="mt-20 mb-10 full-width" style="width: 93%">
      <base-button
        v-if="detail.can_update"
        title="新增年度"
        icon="Plus"
        @click="addYear(2)"
      />
    </div>
    <div class="mt-10" style="width: 90%">
      <el-form
        :model="form"
        label-width="180px"
        :disabled="disabled"
        label-position="left"
        class="form-content flex flex-col"
      >
        <el-form-item
          v-for="(item, index) in investmentCount"
          :key="item"
          label-width="0"
        >
          <div class="flex flex-col flex-center full-width">
            <div class="flex flex-center flex-justify-between full-width">
              <div class="flex-child-average full-width flex flex-center">
                <span style="width: 400px"
                  >{{
                    form.month_plan_investment[index].year
                  }}年度计划纳统投资（万元）</span
                >
                <div class="disable-input" @change="change(item)">
                  {{
                    form.month_plan_investment[index]
                      ? form.month_plan_investment[index].sum
                      : ''
                  }}
                </div>
              </div>
              <div style="width: 20px"></div>
              <div class="flex-child-average full-width flex flex-center">
                <span style="width: 440px"
                  >{{
                    form.month_plan_investment[index].year
                  }}年度累计纳统投资（万元）</span
                >
                <div class="disable-input" @change="change(item)">
                  {{ form.month_investment_amount[index].sum }}
                </div>
                <div
                  class="btnSub pointer"
                  @click="
                    showMonth(form.month_plan_investment[index].year, 2, index)
                  "
                >
                  月填报
                </div>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
    </div>

    <el-dialog
      v-if="current"
      v-model="show"
      :title="
        current.editType === 1
          ? current.year + '年度投资情况'
          : current.year + '年度纳统情况'
      "
      width="1260px"
    >
      <div class="flex flex-center flex-align-start">
        <div>
          <div class="padding-top"></div>
          <div class="padding-top mt-20 mr-10 bold">
            {{ current.editType === 1 ? '月计划投资:' : '月计划纳统投资:' }}
          </div>
          <div class="padding-top mt-10 mr-10 bold">
            {{ current.editType === 1 ? '月完成投资:' : '月完成纳统投资:' }}
          </div>
        </div>
        <div>
          <div class="mr-5 flex flex-center">
            <div v-for="(item, index) in 11" :key="item" class="title">
              <div v-if="index === 0">1-2月</div>
              <div v-else>{{ item + 1 }}月</div>
            </div>
          </div>
          <div class="mr-5 flex flex-center">
            <div v-for="(item, index) in current.planMonths" :key="item.name">
              <input
                class="input"
                v-model="item.data"
                @change="changeMonth(item, 1, index)"
              />
            </div>
          </div>

          <div class="mr-5 flex flex-center">
            <div v-for="(item, index) in current.months" :key="item.name">
              <input
                class="input"
                v-model="item.data"
                @change="changeMonth(item, 2, index)"
              />
            </div>
          </div>
        </div>
      </div>
      <div class="mt-20 full-width flex flex-justify-between">
        <span class="red">* 请按月份进行填报，单位：万元</span>
        <base-button
          class="mr-20"
          title="保存"
          icon="el-icon-check"
          @click="update"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import baseButton from '@/components/base-button.vue'
import { deepClone } from '@/utils/tools.js'

export default {
  name: 'params3',
  components: { baseButton },
  props: {
    info: {
      type: Object,
      default: null
    },
    detail: {
      type: Object,
      default: null
    }
  },
  watch: {
    detail: {
      handler(val) {
        if (Object.keys(val).length > 1) {
          this.init(val)
        }
      },
      immediate: true
    },
    disabled: {
      handler(val) {
        if (val) {
          this.update(val !== true)
        }
      },
      immediate: false
    }
  },
  data() {
    return {
      show: false,
      disabled: true,
      investmentCount: 0,
      completeCount: 0,
      list1: [],
      list2: [],
      form: {},
      current: null
    }
  },
  methods: {
    /**
     *
     * @param type 1计划投资  2 纳统投资
     */
    addYear(type) {
      this.disabled = false
      if (type === 1) {
        if (this.form.month_complete_amount.length === 0) {
          const nowYear = new Date().getFullYear() - 1
          this.form.month_complete_amount.push(this.nextYear(nowYear))
          this.form.month_plan_complete_amount.push(this.nextYear(nowYear))
        } else {
          this.form.month_complete_amount.splice(
            0,
            0,
            this.nextYear(
              Number.parseInt(this.form.month_complete_amount[0].year)
            )
          )
          this.form.month_plan_complete_amount.splice(
            0,
            0,
            this.nextYear(
              Number.parseInt(this.form.month_plan_complete_amount[0].year)
            )
          )
        }
        this.completeCount = this.completeCount + 1
      } else if (type === 2) {
        if (this.form.month_investment_amount.length === 0) {
          const nowYear = new Date().getFullYear() - 1
          this.form.month_investment_amount.push(this.nextYear(nowYear))
          this.form.month_plan_investment.push(this.nextYear(nowYear))
        } else {
          this.form.month_investment_amount.splice(
            0,
            0,
            this.nextYear(
              Number.parseInt(this.form.month_investment_amount[0].year)
            )
          )
          this.form.month_plan_investment.splice(
            0,
            0,
            this.nextYear(
              Number.parseInt(this.form.month_plan_investment[0].year)
            )
          )
        }
        this.investmentCount = this.investmentCount + 1
      }
      console.log(this.form)
    },
    nextYear(year) {
      const tmp2 = {}
      tmp2.year = (year + 1).toString()
      tmp2.sum = ''
      tmp2.monthlyData = []
      for (let i = 1; i <= 12; i++) {
        const item2 = { year: tmp2.year, data: '', month: i.toString() }
        tmp2.monthlyData.push(item2)
      }
      return tmp2
    },
    init(res) {
      if (!Object.keys(res).includes('month_plan_investment')) {
        res.month_plan_investment = []
      }
      if (!Object.keys(res).includes('month_investment_amount')) {
        res.month_investment_amount = []
      }
      if (!Object.keys(res).includes('month_complete_amount')) {
        res.month_complete_amount = []
      }
      if (!Object.keys(res).includes('month_plan_complete_amount')) {
        res.month_plan_complete_amount = []
      }
      this.investmentCount = Math.max(
        res.month_plan_investment.length,
        res.month_investment_amount.length
      )
      // 求出差集
      const dd = res.month_plan_investment
        .filter(sub => {
          return (
            res.month_investment_amount.findIndex(
              ele => sub.year !== ele.year
            ) !== -1
          )
        })
        .map(sub => {
          // data -》 ''
          sub.monthlyData.map(ele => {
            ele.data = ele.data ? ele.data : ''
            return ele
          })
          return sub
        })
      // 复制差集
      if (res.month_plan_investment.length === this.completeCount) {
        dd.forEach(sub => {
          res.month_investment_amount.push(sub)
        })
      } else {
        dd.forEach(sub => {
          res.month_plan_investment.push(sub)
        })
      }

      this.completeCount = Math.max(
        res.month_complete_amount.length,
        res.month_plan_complete_amount.length
      )
      // 求出差集
      const d = res.month_complete_amount
        .filter(sub => {
          return (
            res.month_plan_complete_amount.findIndex(
              ele => sub.year !== ele.year
            ) !== -1
          )
        })
        .map(sub => {
          // data -》 ''
          sub.monthlyData.map(ele => {
            ele.data = ele.data ? ele.data : ''
            return ele
          })
          return sub
        })
      // 复制差集
      console.log(d)
      if (res.month_complete_amount.length === this.completeCount) {
        d.forEach(sub => {
          if (
            res.month_plan_complete_amount.findIndex(
              ele => ele.year === sub.year
            ) === -1
          ) {
            res.month_plan_complete_amount.push(sub)
          }
        })
      } else {
        d.forEach(sub => {
          if (
            res.month_complete_amount.findIndex(
              ele => ele.year === sub.year
            ) === -1
          ) {
            res.month_complete_amount.push(sub)
          }
        })
      }
      this.form = res
    },
    change(item) {
      this.form[item.code] = item.value
      this.form[item.code2] = item.value2
    },
    update(show = Boolean) {
      this.$nextTick(() => {
        this.form.projectId = this.form.id
        if (
          this.form.month_plan_complete_amount[this.current.index] !==
            undefined &&
          this.form.month_plan_complete_amount.length > 0
        ) {
          this.form.month_plan_complete_amount[this.current.index].sum =
            this.getSum(
              this.form.month_plan_complete_amount[this.current.index]
                .monthlyData
            )
        }
        if (
          this.form.month_complete_amount[this.current.index] !== undefined &&
          this.form.month_complete_amount.length > 0
        ) {
          this.form.month_complete_amount[this.current.index].sum = this.getSum(
            this.form.month_complete_amount[this.current.index].monthlyData
          )
        }
        if (
          this.form.month_plan_investment[this.current.index] !== undefined &&
          this.form.month_plan_investment.length > 0
        ) {
          this.form.month_plan_investment[this.current.index].sum = this.getSum(
            this.form.month_plan_investment[this.current.index].monthlyData
          )
        }
        if (
          this.form.month_investment_amount[this.current.index] !== undefined &&
          this.form.month_investment_amount.length > 0
        ) {
          this.form.month_investment_amount[this.current.index].sum =
            this.getSum(
              this.form.month_investment_amount[this.current.index].monthlyData
            )
        }
        // 生成年月字段
        this.initYearMonth(
          this.form.month_plan_complete_amount,
          '_month_plan_complete_amount',
          '_yearly_plan_complete_amount'
        )
        this.initYearMonth(
          this.form.month_complete_amount,
          '_month_complete_amount',
          '_yearly_complete_amount'
        )
        this.initYearMonth(
          this.form.month_plan_investment,
          '_month_plan_investment',
          '_yearly_plan_investment'
        )
        this.initYearMonth(
          this.form.month_investment_amount,
          '_month_investment_amount',
          '_yearly_complete_investment'
        )
        delete this.form._id
        this.$api.project.proUpdate(this.detail).then(res => {
          if (res.code === 200) {
            if (show) {
              this.$message.success(res.msg)
              this.show = false
            }
          } else {
            this.$message.error(res.msg)
          }
        })
      })
    },

    /**
     * 组合字段
     * @param list
     * @param key 月度关键词
     * @param key1 年度关键词
     */
    initYearMonth(list, key, key1) {
      if (list.length > 0) {
        list.forEach(sub => {
          let tmp = this.kv(sub.year + key1, sub.sum)
          sub.monthlyData.forEach(res => {
            const month = this.kv(res.year + '_' + res.month + key, res.data)
            tmp = Object.assign(tmp, month)
          })
          this.form = Object.assign(this.form, tmp)
        })
      }
    },
    kv(key, value) {
      const keyValue = {}
      keyValue[key] = value
      return keyValue
    },

    /**
     *
     * @param year
     * @param type 1 年度投资  2 纳统投资
     * @param index 索引
     */
    showMonth(year, type, index) {
      this.$nextTick(() => {
        const item = { editType: type, year, index, planMonths: [], months: [] }
        if (type === 1) {
          this.form.month_plan_complete_amount
            .find(sub => sub.year === year)
            .monthlyData.forEach(sub => {
              item.planMonths.push(deepClone(sub))
            })
          this.form.month_complete_amount
            .find(sub => sub.year === year)
            .monthlyData.forEach(sub => {
              item.months.push(deepClone(sub))
            })
        } else if (type === 2) {
          this.form.month_plan_investment
            .find(sub => sub.year === year)
            .monthlyData.forEach(sub => {
              item.planMonths.push(deepClone(sub))
            })
          this.form.month_investment_amount
            .find(sub => sub.year === year)
            .monthlyData.forEach(sub => {
              item.months.push(deepClone(sub))
            })
        }
        this.current = Object.assign({}, item)
        for (let i = 1; i <= 11; i++) {
          const index = this.current.months.findIndex(
            sub => sub.month === i.toString()
          )
          if (index === -1 && this.current.months.length < 11) {
            const ele = { month: i.toString(), data: '', year: '' }
            this.current.months.push(ele)
          }
          const planIndex = this.current.planMonths.findIndex(
            sub => sub.month === i.toString()
          )
          if (planIndex === -1 && this.current.planMonths.length < 11) {
            const sub = { month: i.toString(), data: '', year: '' }
            this.current.planMonths.push(sub)
          }
        }
      })
      this.show = !this.show
    },
    /**
     *
     * @param res
     * @param type 1 计划 2 累计
     * current 1 年度投资 2 纳统投资
     */
    changeMonth(res, type, index) {
      setTimeout(() => {
        if (this.current.editType === 1) {
          if (type === 1) {
            this.form.month_plan_complete_amount[
              this.current.index
            ].monthlyData[index] = res
          } else {
            this.form.month_complete_amount[this.current.index].monthlyData[
              index
            ] = res
          }
        } else if (this.current.editType === 2) {
          if (type === 1) {
            this.form.month_plan_investment[this.current.index].monthlyData[
              index
            ] = res
          } else {
            this.form.month_investment_amount[this.current.index].monthlyData[
              index
            ] = res
          }
        }
      }, 1000)
    },
    getSum(list) {
      let sum = 0
      list.forEach(sub => {
        if (sub.data.length > 0) {
          sum = sum + Number.parseInt(sub.data)
        }
      })
      return sum
    }
  }
}
</script>

<style lang="scss" scoped>
.form-content {
  border: 1px solid #eeeeee;
  padding: 20px;

  :deep(.el-input.is-disabled .el-input__inner) {
    color: #343434;
  }

  :deep(.el-textarea.is-disabled .el-textarea__inner) {
    color: #343434;
  }
}

.grid {
  display: grid;
  grid-template-columns: auto auto;
  grid-column-gap: 20px;
}

.title {
  width: 70px;
  padding: 0 11px;
  margin-bottom: 10px;
  font-weight: bold;
}

.input {
  width: 70px;
  height: 30px;
  border: #e7e7e7 solid 1px;
  padding: 0 10px;
  border-right: none;
}

.input:last-child {
  width: 70px;
  height: 40px;
  padding: 0 10px;
  border-right: #e7e7e7 solid 1px;
}

.disable-input {
  height: 30px;
  width: 100%;
  border-radius: 4px;
  background-color: #f5f7fa;
  border: #e6e8ed solid 1px;
  text-align: left;
  padding: 0 10px;
  color: #343434;
}

.btnSub {
  color: white;
  width: 120px;
  margin-left: 10px;
  height: 30px;
  background-color: #edac56;
  border-radius: 30px;
  padding: 0 10px;
}
</style>
