<template>
  <div>
    <div class="tool-btn" style="width: 800px; margin: 0 auto; text-align: right;">
      <el-button size="small" type="primary" icon="el-icon-printer" v-print="'#changeDoc'" :disabled="!disabled">打印</el-button>
    </div>
    <div id="changeDoc" class="doc-page">
      <h3 class="page-title">项目变更申请表</h3>
      <table>
        <tbody>
          <tr>
            <td class="doc-label">研发项目名称</td>
            <td class="doc-input">
              <project-select v-model="currProjectId" @change="handleProjectChange" :disabled="disabled"></project-select>
            </td>
            <td class="doc-label">研发项目编号</td>
            <td class="doc-input">{{ selProject.xmbh }}</td>
          </tr>
          <tr>
            <td class="doc-label">项目负责人</td>
            <td class="doc-input">{{ selProject.xmfzrxm }} </td>
            <td class="doc-label">项目申请单位</td>
            <td class="doc-input">{{ selProject.xmsqdw }}</td>
          </tr>

          <tr>
            <td class="doc-label">变更类型</td>
            <td class="doc-input" colspan="3">
              <avue-select
                v-model="formData.zdmc"
                placeholder="请选择"
                :dic="changeTypeList"
                style="width: 100%"
                :disabled="disabled || !selProject.id"
              ></avue-select>
            </td>
          </tr>

          <tr>
            <td class="doc-label">变更前</td>
            <td class="doc-input" style="padding: 0;">
              <!-- 项目预算 -->
              <template v-if="formData.zdmc === 'xmyszemx'">
                <div style="height: 31px; line-height: 31px; border-bottom: 1px solid #000;">总计：{{ selProject.xmysze }}万元</div>
                <div class="year-list">
                  <div class="year-list-item" v-for="item of oldXmyszemxList" :key="item.year">
                    <div class="year" >{{ item.year }}</div>
                    <div class="year-input"> {{ item.amount }} </div>
                  </div>
                </div>
              </template>
              <span v-else>{{ getChangeBeforeVal }}</span>
            </td>
            <td class="doc-label">变更后</td>
            <td class="doc-input">
              <el-input v-if="formData.zdmc === 'xmmc'" placeholder="请输入项目名称" v-model="formData.bghdz" :disabled="disabled" />
              <!-- 项目结束时间 -->
              <el-date-picker
                v-if="'xmjssj'.indexOf(formData.zdmc) > -1"
                v-model="formData.bghdz"
                format="yyyy年MM月dd日"
                value-format="yyyy-MM-dd"
                placeholder="请选择日期"
                style="width: 100%"
                :disabled="disabled"
                @change="handleEndDateChange"
              ></el-date-picker>
              <!-- 项目负责人 -->
              <template v-if="formData.zdmc === 'xmfzr'">
                <person-select
                  v-if="!disabled"
                  v-model="formData.bghdz"
                  :yearAndMonth="projectStartMonth"
                  valueKey="id"
                  :disabled="disabled"
                  style="width: 100%"
                />
                <span v-else>{{ formData.bghdz }}</span>
              </template>
              
              <!-- 项目状态 -->
              <avue-select
                v-if="formData.zdmc === 'status'"
                v-model="formData.bghdz"
                placeholder="请选择"
                :dic="projectStateList"
                style="width: 100%"
                :disabled="disabled"
              ></avue-select>
              <!-- 所属二级单位 -->
              <template v-if="formData.zdmc === 'xmsqdwid'">
                <second-unit-cascader
                  v-if="!disabled"
                  v-model="formData.bghdz"
                  :disabled="disabled"
                  :yearAndMonth="currProjectYear"
                  style="width: 100%;"
                />
                <span v-else>{{ formData.bghdz }}</span>
              </template>
              
              <!-- 项目预算明细 -->
              <div v-if="formData.zdmc === 'xmyszemx'" class="year-list">
                <div style="height: 31px; line-height: 31px; border-bottom: 1px solid #000;">总计：{{ newXmysTotal }}万元</div>
                <div class="year-list-item" v-for="item of newXmyszemxList" :key="item.year">
                  <div class="year" >{{ item.year }}</div>
                  <div class="year-input">
                    <input v-model="item.amount" type="number" style="padding: 0 6px;" :disabled="disabled" />
                  </div>
                </div>
              </div>
            </td>
          </tr>
          
          <!-- 变更结束时间，同时增加预算变更 -->
          <tr v-if="formData.zdmc === 'xmjssj' && !disabled"><td colspan="4" align="center" style="height: 46px; font-weight: 600;">预算变更</td></tr>
          <tr v-if="formData.zdmc === 'xmjssj' && !disabled">
            <td class="doc-label">变更前</td>
            <td class="doc-input" style="padding: 0;">
              <div style="height: 31px; line-height: 31px; border-bottom: 1px solid #000;">总计：{{ selProject.xmysze }}万元</div>
              <div class="year-list">
                <div class="year-list-item" v-for="item of oldXmyszemxList" :key="item.year">
                  <div class="year">{{ item.year }}</div>
                  <div class="year-input"> {{ item.amount }} </div>
                </div>
              </div>
            </td>
            <td class="doc-label">变更后</td>
            <td class="doc-input" style="padding: 0;">
              <div class="year-list">
                <div style="height: 31px; line-height: 31px; border-bottom: 1px solid #000;">总计：{{ newXmysTotal }}万元</div>
                <div class="year-list-item" v-for="item of newXmyszemxList" :key="item.year">
                  <div class="year">{{ item.year }}</div>
                  <div class="year-input">
                    <input v-model="item.amount" type="number" style="padding: 0 6px;" :disabled="disabled" />
                  </div>
                </div>
              </div>
            </td>
          </tr>

          <tr>
            <td class="doc-label">变更原因说明</td>
            <td class="doc-input" colspan="3">
              <el-input v-model="formData.bgyy" type="textarea" :rows="3" :disabled="disabled" />
            </td>
          </tr>

          <tr>
            <td class="doc-label">变更生效时间</td>
            <td class="doc-input" colspan="3">
              <el-date-picker
                v-model="formData.bgsxsj"
                format="yyyy年MM月dd日"
                value-format="yyyy-MM-dd"
                placeholder="请选择日期"
                style="width: 100%"
                :disabled="disabled"
              ></el-date-picker>
            </td>
          </tr>

          <tr>
            <td class="doc-label">附件上传</td>
            <td class="doc-input" colspan="3" style="text-align: left;">
              <avue-upload
                v-if="!disabled"
                action="/api/kd-resource/oss/endpoint/put-file"
                dataType="object"
                :props-http="{
                  url: 'link',
                  name: 'originalName',
                  res: 'data',
                }"
                type="upload"
                v-model="formData.attachment"
                style="margin: 14px 0 14px 12px;"
                :disabled="disabled"
                :uploadPreview="handleUploadPreview"
              ></avue-upload>
              <div v-else>
                <div v-for="(item, index) of formData.attachment" :key="index" style="line-height: 26px; padding: 6px;">
                  <el-link type="primary" @click="handleDownFile(item)">{{ item.label }}</el-link>
                </div>
              </div>
            </td>
          </tr>
        </tbody>
      </table>

      <div v-if="!disabled" class="btn-wrap" style="text-align: center; margin-top: 30px;">
        <el-button type="primary" style="width: 160px;" @click="handleSaveBtn">保存</el-button>
      </div>
  </div>
  </div>
</template>

<script>
import { getDictionary } from "@/api/system/dict";
import { getList as getTechnicanRosterList } from "@/api/basicResource/technicianRoster";
import { save } from "@/api/projectManage/change";
import moment from "moment";
import projectSelect from "@/components/project-select";
import secondUnitCascader from "@/components/second-unit-cascader";
import personSelect from "@/components/person-select";
import Decimal from "decimal.js";
import { downloadFileByUrl } from "@/util/util";

export default {
  props: {
    projectId: [String, Number],
    data: Object,
    disabled: {
      type: Boolean,
      type: false
    }
  },
  components: {
    projectSelect,
    secondUnitCascader,
    personSelect
  },
  data() {
    return {
      currProjectId: '',
      formData: {
        attachment: []
      },
      // 变更类型
      changeTypeList: [],

      // 项目状态
      projectStateList: [],

      loading: false,
      selProject: {},

      // 项目负责人列表
      fzrList: [],

      // 变更前预算明细
      oldXmyszemxList: [],
      // 变更后预算明细
      newXmyszemxList: [],

      // 项目开始月份
      projectStartMonth: ""
    };
  },
  watch: {
    "formData.zdmc"(newVal) {
      if (newVal == 'xmfzr') {
        this.getTechnicanRosterListFunc(moment(this.selProject.xmkssj).format('yyyyMM'));
      }
      // else if (newVal == 'xmyszemx' || newVal == 'xmjssj') {
      //   this.oldXmyszemxList = JSON.parse(this.selProject.xmyszemx);
      //   this.newXmyszemxList = JSON.parse(this.selProject.xmyszemx);
      // }
    },
  },
  computed: {
    // 当前项目所属年份
    currProjectYear() {
      return this.selProject.xmkssj ? moment(this.selProject.xmkssj).format('YYYY') : '';
    },
    // 获取变更前的值
    getChangeBeforeVal() {
      if (this.disabled) {
        return this.formData.bgqdz;
      }
      
      if (this.formData.zdmc === 'xmfzr') {
        return this.selProject.xmfzrxm;
      } else if (this.formData.zdmc === 'xmsqdwid') {
        return this.selProject.xmsqdw;
      } else if (this.formData.zdmc === 'status') {
        let _currStatusObj = this.projectStateList.find(item => item.value == this.selProject.status);
        return _currStatusObj ? _currStatusObj.label: '';
      } else {
        return this.selProject[this.formData.zdmc];
      }
    },
    // 变更后的预算总值
    newXmysTotal() {
      let total = new Decimal(0);
      this.newXmyszemxList.forEach(item => {
        total = total.add(new Decimal(item.amount || 0));
      });
      return total;
    },
  },
  mounted() {
    this.getDictList("xm_biangeng_field", "changeTypeList");
    this.getDictList("project_state", "projectStateList");
    this.currProjectId = this.projectId;

    if (Object.keys(this.data).length) {
      this.formData = { ...this.data, zdmc: this.data.zdmc.toLowerCase() };
      if (this.formData.zdmc === 'xmyszemx') {
        this.oldXmyszemxList = this.formData.bgqdzJSON;
        this.newXmyszemxList = this.formData.bghdzJSON;
      }
      this.currProjectId = this.data.xmId;
    }
    
  },
  methods: {
    handleEndDateChange(e) {
      let startYear = moment(this.selProject.xmkssj).format('YYYY');
      let endYear = moment(e).format('YYYY');
      
      let newYearList = [];
      for (let i=startYear; i<=endYear; i++) {
        let _obj = this.oldXmyszemxList.find(item => item.year == i);
        newYearList.push({ year: i, amount: _obj ? _obj.amount : '' });
      }
      this.newXmyszemxList = newYearList;
    },
    /**
     * 获取人员花名册
     */
    getTechnicanRosterListFunc(yearAndMonth) {
      getTechnicanRosterList(1, 99999, { yearAndMonth }).then(res => {
        if (res.data.success) {
          this.fzrList = res.data.data.records.map(item => {
            return { label: item.name, value: item.id };
          });
        }
      });
    },
    getDictList(code, toListKey) {
      getDictionary({ code }).then((res) => {
        this[toListKey] = res.data.data.map((item) => {
          return { label: item.dictValue, value: item.dictKey.toLowerCase() };
        });
      });
    },
    handleProjectChange(data) {
      this.selProject = data;

      this.projectStartMonth = moment(data.xmkssj).format("yyyyMM");
      if (!this.disabled) {
        this.oldXmyszemxList = JSON.parse(data.xmyszemx);
        this.newXmyszemxList = JSON.parse(data.xmyszemx);
      }
    },
    validForm() {
      let errorText = '';
      if (!this.currProjectId) {
        errorText = '请选择变更的项目';
      } else if (!this.formData.zdmc) {
        errorText = '请选择变更类型';
      } else if (!this.formData.bgyy) {
        errorText = '请输入变更原因';
      } else if (!this.formData.bgsxsj) {
        errorText = '请选择变更生效时间';
      }

      if ('xmyszemx,xmjssj'.indexOf(this.formData.zdmc) > -1) {
        for (let i=0; i<this.newXmyszemxList.length; i++) {
          let _item = this.newXmyszemxList[i];
          if (_item.amount === null || _item.amount === undefined || _item.amount === '') {
            errorText = `请填写${_item.year}年的预算`;
            break;
          }
        }
        if (this.formData.zdmc === 'xmjssj' && !this.formData.bghdz) {
          errorText = '变更后的值不能为空!';
        }
      } else {
        if (!this.formData.bghdz || (this.formData.bghdz instanceof Array && !this.formData.bghdz.length)) {
          errorText = '变更后的值不能为空!';
        }
      }
      
      return errorText;
    },
    /**
     * 获取提交的参数
     * @param changeType 变更类型
     */
    getFormData(changeType) {
      const params = {
        ...this.formData,
        bgqdz: this.selProject[changeType],
        attachment: JSON.stringify(this.formData.attachment),
        xmId: this.currProjectId,
        zdmc: changeType.toUpperCase()
      };
      if (changeType === 'xmyszemx') {
        params.bghdz = JSON.stringify(this.newXmyszemxList);
      } else if (changeType === 'xmsqdwid') {
        params.bghdz = params.bghdz[params.bghdz.length - 1];
      }
      return params;
    },
    handleSaveBtn() {
      let errorText = this.validForm();
      if (errorText) {
        this.$message.error(errorText+'！');
        return;
      }

      if (this.formData.zdmc === 'xmjssj' && JSON.stringify(this.newXmyszemxList) != JSON.stringify(this.oldXmyszemxList)) {
        this.$confirm('检测到预算发生变化，点击确定，将同时发起一个预算变更，确认要操作吗？', '提示').then(() => {
          const params1 = this.getFormData(this.formData.zdmc);
          const params2 = this.getFormData('xmyszemx');
          params2.bgqdz = JSON.stringify(this.oldXmyszemxList);

          Promise.all([this.saveData(params1), this.saveData(params2)]).then(([res1, res2]) => {
            if (res1.data.success) {
              this.$message.success("保存成功!");
              this.$emit("success");
            }
          });
        });
        return;
      }

      const params = this.getFormData(this.formData.zdmc);

      this.saveData(params).then(({ data }) => {
        if (data.code == 200) {
          this.$message.success("保存成功!");
          this.$emit("success");
        }
      });
    },
    saveData(params) {
      return save(params)
    },
    handleDownFile(file) {
      downloadFileByUrl(file.value, file.label);
    },
    handleUploadPreview (file, column, done) {
      downloadFileByUrl(file.url, file.name);
      return;
    },
  },
};
</script>

<style lang="scss" scoped>
.page-title {
  text-align: center;
  font-size: 24px;
  padding: 24px 0 16px;
  margin: 0;
}

.doc-page {
  width: 800px;
  margin: 0 auto;
}
table {
  width: 100%;
  border: 1px solid #333;
}
.doc-label {
  text-align: center;
  padding: 6px;
  color: #777;
  font-size: 14px;
  width: 15%;
}
.doc-input {
  text-align: center;
  color: #333;
  width: 35%;
  height: 40px;
}

.el-input__inner {
  border: none;
}
tr td {
  border: 1px solid #333;
}

.year-list {
  &-item {
    display: flex;
    height: 32px;
    line-height: 32px;
    border-bottom: 1px solid #333;
    &:last-child {
      border-bottom: 0;
    }
    .year {
      width: 65px;
      border-right: 1px solid #333;
    }
    .year-input {
      padding-left: 12px;
      input {
        border: none;
      }
    }
  }
  
}
</style>
