<template>
  <div class="app-container" v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="180px">
      <table class="table_register" style="width: 100%;">
        <tr>
          <th colspan="4" class="th_title">年度基本信息（<b style="color: red;">年度销售收入、研发投入、职工总人数、研发人员请填写正整数，占销售收入比例为系统自动算出</b>）</th>
        </tr>
        <tr>
          <th>企业名称</th>
          <td>
            <el-form-item prop="entName" label-width="0">
              <el-input v-model="form.entName" type="text" placeholder="请输入企业名称" :disabled="disabledVisible"></el-input>
            </el-form-item>
          </td>
          <th><span style="color: red;">*</span>申办加计年度</th>
          <td>
            <el-form-item prop="projectYear" label-width="0">
              <el-select v-model="form.projectYear" filterable :disabled="yearVisible" @change="handleYear">
                <el-option v-for="(item, index) in yearsOptions" :key="index" :value="item.dictValue" :label="item.dictLabel"></el-option>
              </el-select>
            </el-form-item>
          </td>
        </tr>
        <tr>
          <th>通信地址</th>
          <td colspan="3">
            <el-form-item prop="address" label-width="0">
              <el-input v-model="form.address" placeholder="请输入通讯地址" :disabled="disabledVisible"></el-input>
            </el-form-item>
          </td>
        </tr>
        <tr>
          <th>企业联系人</th>
          <td>
            <el-form-item prop="linkName" label-width="0">
              <el-input v-model="form.linkName" placeholder="请输入企业联系人" :disabled="disabledVisible"></el-input>
            </el-form-item>
          </td>
          <th>联系电话（座机）</th>
          <td>
            <el-form-item prop="linkPhone" label-width="0">
              <el-input v-model="form.linkPhone" type="text" auto-complete="off" placeholder="请输入联系电话(座机)" :disabled="disabledVisible">
              </el-input>
            </el-form-item>
          </td>
        </tr>
        <tr>
          <th>联系电话（手机）</th>
          <td>
            <el-form-item prop="linkMobile" label-width="0">
              <el-input v-model="form.linkMobile" type="text" auto-complete="off" placeholder="请输入联系电话(手机)" :disabled="disabledVisible">
              </el-input>
            </el-form-item>
          </td>
          <th><span style="color: red;">*</span>职工总人数(人)</th>
          <td>
            <el-form-item prop="totoalPersons" label-width="0">
              <el-input v-model="form.totoalPersons" type="text" auto-complete="off" placeholder="请输入职工总人数" :disabled="disabledVisible">
              </el-input>
            </el-form-item>
          </td>
        </tr>
        <tr>
          <th><span style="color: red;">*</span>年度企业销售收入(万元)</th>
          <td>
            <el-form-item prop="sales" label-width="0">
              <el-input v-model="form.sales" type="text" auto-complete="off" placeholder="请输入年度企业销售收入(万元)" :disabled="disabledVisible">
              </el-input>
            </el-form-item>
          </td>
          <th><span style="color: red;">*</span>研发人数（人）</th>
          <td>
            <el-form-item prop="techPersons" label-width="0">
              <el-input v-model="form.techPersons" type="text" auto-complete="off" placeholder="请输入研发人数" :disabled="disabledVisible">
              </el-input>
            </el-form-item>
          </td>
        </tr>
        <tr>
          <th><span style="color: red;">*</span>年度研发投入(万元)</th>
          <td>
            <el-form-item prop="techInvest" label-width="0">
              <el-input v-model="form.techInvest" type="text" auto-complete="off" placeholder="请输入年度研发投入(万元)" :disabled="disabledVisible">
              </el-input>
            </el-form-item>
          </td>
          <th>占销售收入比例(%)</th>
          <td>
            <el-form-item prop="techRate" label-width="0">
              <el-input v-model="form.techRate" type="text" auto-complete="off" placeholder="请输入占销售收入比例(%)" disabled>
              </el-input>
            </el-form-item>
          </td>
        </tr>
        <tr>
          <th><span style="color: red;">*</span>企业所属行业</th>
          <td>
            <el-form-item prop="industryArray" label-width="0">
              <el-cascader
                  v-model="form.industryArray"
                  :options="options"
                  :disabled="disabledVisible"></el-cascader>
            </el-form-item>
          </td>
          <th><span style="color: red;">*</span>国家自主创新示范区企业</th>
          <td>
            <el-form-item prop="innovateFlag" label-width="0">
              <el-radio-group v-model="form.innovateFlag" :disabled="disabledVisible">
                <el-radio v-for="(item, index) in booleanOptions" :key="index" :label="item.dictValue">{{item.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </td>
        </tr>
      </table>
      <table class="table_register mt20" style="width: 100%;">
        <tr>
          <th colspan="4" class="th_title">科技型中小企业信息</th>
        </tr>
        <tr>
          <th><span style="color: red;">*</span>是否科技型中小企业</th>
          <td>
            <el-form-item prop="smallFlag" label-width="0">
              <el-radio-group v-model="form.smallFlag" :disabled="disabledVisible">
                <el-radio v-for="(item, index) in booleanOptions" :key="index" :label="item.dictValue">{{item.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </td>
        </tr>
      </table>
      <table class="table_register mt20" style="width: 100%;">
        <tr>
          <th colspan="4" class="th_title">高新技术企业信息</th>
        </tr>
        <tr>
           <th><span style="color: red;">*</span>是否高新技术企业</th>
           <td>
             <el-form-item prop="techFlag" label-width="0">
               <el-radio-group v-model="form.techFlag" :disabled="disabledVisible">
                 <el-radio v-for="(item, index) in booleanOptions" :key="index" :label="item.dictValue">{{item.dictLabel}}</el-radio>
               </el-radio-group>
             </el-form-item>
           </td>
        </tr>
        <template v-if="form.techFlag == 1">
          <tr>
            <th><span style="color: red;">*</span>高新技术企业所属技术领域</th>
            <td colspan="3">
              <el-form-item prop="techScopeArray" label-width="0">
                <el-checkbox-group v-model="form.techScopeArray" :disabled="disabledVisible">
                  <el-checkbox v-for="(item, index) in techScopeOptions" :label="item.dictLabel" :key="index">{{item.dictLabel}}</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </td>
          </tr>
          <tr>
            <th><span style="color: red;">*</span>证书有效期限</th>
            <td>
              <el-form-item prop="licenseTime" label-width="0">
                <el-input  @focus="getLayDate" id="licenseTime" v-model="form.licenseTime" clearable></el-input>
              </el-form-item>
            </td>
          </tr>
          <tr>
            <th><span style="color: red;">*</span>高新证书</th>
            <td colspan="3">
              <el-form-item prop="techLicense" ref="techLicenseUpload" label-width="0">
                <FileUpload :file="{url: form.techLicense, name: form.fileName}" @input="handleSuccess" :disabledVisible="disabledVisible">上传证书</FileUpload>
              </el-form-item>
            </td>
          </tr>
        </template>
      </table>
      <h3 class="toolbar">
        <span class="title">研发项目情况表</span>
      </h3>
      <el-table v-loading="tableLoading" :data="list" border>
        <el-table-column label="项目名称" prop="projectName"></el-table-column>
        <el-table-column label="项目起止时间" align="center">
          <template slot-scope="scope">
            <span>{{scope.row.projectStartDate}} - {{scope.row.projectEndDate}}</span>
          </template>
        </el-table-column>
        <el-table-column label="研发人员数" prop="projectName" align="center"/>
      </el-table>
      <template v-if="type == 'year' || type == 'update'">
        <el-row :gutter="40" v-if="!disabledVisible">
          <el-col :span="24">
            <el-form-item style="width:100%;text-align: center;" label-width="0px" class="mt20">
              <el-button :loading="loading" size="medium" type="primary" @click.native.prevent="submitForm" style="width: 100px;">保存</el-button>
              <el-button size="medium" type="primary" style="width: 100px;" @click="cancel">取消</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </template>
    </el-form>

  </div>
</template>

<script>
import { editProjectApi,getProjectInfoApi,synTechApi,draftApi,yearApi,devProjectApi,getYearDataApi,yearUpdateApi,listProjectApi,getYearApi } from "@/api/enterprise/project/project"
import { techScopeOptions,yesOrNoOptions,businessIndustryOptions,booleanOptions } from "@/utils/dataFormat"
import FileUpload from '@/components/FileUpload'
import { listEntUserApi } from "@/api/ent/ent"
import { validAmount,validNumber,validPercentage} from '@/utils/validate'

export default {
  name: "First",
  components: {
    FileUpload
  },
  props: {
    type: {
      type: String
    },
    info: {
      type: Object,
      default: function () {
        return {}
      }
    },
  },
  computed: {
    userType() {
      return this.$store.state.user.userType
    },
    tempVariable() {
      if(this.form.techInvest && this.form.sales) {
        let invest = this.form.techInvest
        let sales = this.form.sales
        return {invest, sales}
      }
    },
    roleTypeFlag() {
      let roleType = this.$store.state.user.userType
      return ['ENT_ADMIN_TECH', 'ENT_ADMIN_FIN', 'ENT_TECH', 'ENT_FIN'].includes(roleType) //判断是否为技术负责人，财务负责人
    }
  },
  data() {
    return {
      yearVisible: false,
      options: businessIndustryOptions,
      tableLoading: false,
      disabledVisible: false,
      entId: "",
      serviceDate: [],
      provinceName: "",
      cityName: "",
      districtName: "",
      codeUrl: "",
      techScopeOptions: techScopeOptions,
      yesOrNoOptions: yesOrNoOptions,
      booleanOptions: booleanOptions,
      provinceDataList: [],
      cityDataList: [],
      districtDataList: [],
      yearsOptions: [],
      list: [],
      form: {
        projectYear: "",
        techScopeArray: [],
        licenseTime: "",
        projectTime: "",
        id: undefined,
        projectOwner: 2,
        techStartDate: "",
        techEndDate: "",
        projectStartDate: "",
        projectEndDate: "",
        industryArray: [],
        industry: "",
        entName: "",
        address: "",
        linkName: "",
        linkPhone: "",
        sales: "",
        techPersons: "",
        innovateFlag: false,
        totoalPersons: "",
        techFlag: false,
        techInvest: undefined
      },
      rules: {
        totoalPersons: [
          { required: true, trigger: "blur", message: "请输入职工总人数" },
          { validator: validNumber, trigger: 'blur'}
        ],
        sales: [
          { required: true, trigger: "blur", message: "请输入年度企业销售收入(万元)" },
          { validator: validAmount, trigger: 'blur'}
        ],
        techPersons: [
          { required: true, trigger: "blur", message: "请输入研发人数" },
          { validator: validNumber, trigger: 'blur'}
        ],
        techInvest: [
          { required: true, trigger: "blur", message: "请输入年度研发投入(万元)" },
          { validator: validAmount, trigger: 'blur'}
        ],
        // techRate: [
        //   { required: true, trigger: "blur", message: "请输入占销售收入比例(%)" },
        //   { validator: validPercentage, trigger: 'blur'}
        // ],
        industry: [
          { required: true, trigger: "blur", message: "请选择企业所属行业" }
        ],
        innovateFlag: [
          { required: true, trigger: "[blur,change]", message: "请选择国家自主创新示范区企业" }
        ],
        overYearFlag: [
          { required: true, trigger: "change", message: "请选择是否跨年" }
        ],
        smallFlag: [
          { required: true, trigger: "[blur,change]", message: "请选择是否科技型中小企业" }
        ],
        techFlag: [
          { required: true, trigger: "[blur,change]", message: "请选择是否高新技术企业" }
        ],
        // techLicense: [
        //   { required: true, trigger: "change", message: "请上传高新企业证书" }
        // ],
        // licenseTime: [
        //   { required: true, trigger: "change", message: "请选择证书有效期限" }
        // ]
      },
      loading: false,
      captchaOnOff: true
    };
  },
  mounted() {
    let laydate = window.laydate;
    laydate.render({
      elem: '#inputUI', // 输入框的id属性，用来绑定到dom
      type: 'date',
      range: true,
      done: (value) => {
        this.form.projectTime = value; // 将选中的值赋给组件中的变量
      }
    });
  },
  created() {
    this.$nextTick(() => {
    	this.$refs.form.clearValidate()
    })
    this.form.id = this.$route.query.id || undefined;
    this.entId = this.$route.query.entId || undefined;
    this.getYears()
    //添加年度信息 获取企业信息

    //如果是财务、科技
    if(this.roleTypeFlag) {
      this.disabledVisible = true
      this.yearVisible = true
    }else {
      this.disabledVisible = false
      this.yearVisible = false
    }
    if(this.type == 'view') {
      this.disabledVisible = true
      this.yearVisible = true
    }
    if(this.type == 'year') {
      this.getEntData()
    }
    if(this.type == 'update') {
      this.yearVisible = true
    }
  },
  methods: {
    getYears(){
      let optionsArray = new Array();
      let years= new Date().getFullYear();
      for(var i=years;i>=years-3;i--){
        let anOption = {};
        anOption.dictValue=i;
        anOption.dictLabel=i;
        optionsArray.push(anOption);
      }
      this.yearsOptions = optionsArray;
      console.log(this.yearsOptions, "this.yearsOptions")
    },
    getLayDate(){
      let _self = this
      laydate.render({
        elem: '#licenseTime', // 输入框的id属性，用来绑定到dom
        type: 'date',
        range: true,
        done: (value) => {
          _self.form.licenseTime = value; // 将选中的值赋给组件中的变量
        }
      })
    },
    getEntData(e) {
      listEntUserApi().then(res => {
        this.form = {}
        if(res.code == 200) {
          if(e) {
            this.form.projectYear = e
          }
          console.log("$$$$$$$$$$$$")
          this.form.entName = res.data.entName
          this.form.linkName = res.data.linkName
          this.form.linkPhone = res.data.linkPhone
          this.form.linkMobile = res.data.linkMobile
          this.form.techFlag = res.data.techFlag
          this.form.address = res.data.address
        }
      })
    },
    getYearData(projectYear) {
      getYearDataApi(projectYear, this.entId).then(res => {
        this.form = res.data
        this.form.fileName = '高新证书'
        if(this.form.techStartDate && this.form.techEndDate) {
          this.form.licenseTime = this.form.techStartDate + ' 至 ' + this.form.techEndDate
        }
        if(this.form.techScope) {
          let techScope = this.form.techScope.split(',') || []
          this.$set(this.form, 'techScopeArray', techScope)
        }
        if(this.form.industry) {
          let industryArray = this.form.industry.split(',') || [];
          this.$set(this.form, 'industryArray', industryArray);
        }
      })
    },
    handleYear(e) {
      getYearApi(e).then(res => {
        if(res.data) {
          this.form = res.data
          this.form.fileName = '高新证书'
          if(this.form.techStartDate && this.form.techEndDate) {
            this.form.licenseTime = this.form.techStartDate + ' 至 ' + this.form.techEndDate
          }
          if(this.form.techScope) {
            let techScope = this.form.techScope.split(',') || []
            this.$set(this.form, 'techScopeArray', techScope)
          }
          if(this.form.industry) {
            let industryArray = this.form.industry.split(',') || [];
            this.$set(this.form, 'industryArray', industryArray);
          }
        }else {
          this.getEntData(e)
        }
      })
    },
    getList(year) {
      this.tableLoading = true;
      let params = {
        year: year,
        entId: this.entId
      }
      listProjectApi(params).then(response => {
        this.list = response.data.records;
        this.total = response.data.total;
        this.tableLoading = false;
      });
    },
    handleSuccess(file) {
      this.$refs.techLicenseUpload.clearValidate()
      this.form.techLicense = file.url;
      this.form.fileName = file.name;
    },
    cancel() {
      this.$store.dispatch("tagsView/delView", this.$route); // 关闭当前tab
      this.$router.go(-1);
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if(valid) {
          this.loading = true
          if(this.form.techScopeArray && this.form.techScopeArray.length > 0) {
            this.form.techScope = this.form.techScopeArray.join(',')
          }
          this.form.industry = this.form.industryArray.join(',')
          if(this.form.projectTime) {
            this.form.projectStartDate = this.form.projectTime.split('至')[0].trim()
            this.form.projectEndDate = this.form.projectTime.split('至')[1].trim()
          }else {
            this.form.projectStartDate = ""
            this.form.projectEndDate = ""
          }
          if(this.form.licenseTime) {
            this.form.techStartDate = this.form.licenseTime.split('至')[0].trim()
            this.form.techEndDate = this.form.licenseTime.split('至')[1].trim()
          }else{
            this.form.techStartDate = ""
            this.form.techEndDate = ""
          }
          let _self = this;
          this.$confirm('是否确认保存？', "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(function() {
            if(_self.type == 'year') {
              yearApi(_self.form).then(res => {
                _self.$alert('企业加计年度企业基本信息保存成功', '提示', {
                  confirmButtonText: '确定',
                  callback: action => {
                    _self.loading = false
                    _self.$store.dispatch("tagsView/delView", _self.$route);
                    _self.$router.go(-1);
                  }
                })
              })
            } else {
              yearUpdateApi(_self.form).then(res => {
                _self.$alert('企业加计年度企业基本信息保存成功', '提示', {
                  confirmButtonText: '确定',
                  callback: action => {
                    _self.loading = false
                    _self.$store.dispatch("tagsView/delView", _self.$route);
                    _self.$router.go(-1);
                  }
                })
              })
            }
          }).catch(() => {
              _self.loading = false
          });
        }
      })
    }
  },
  watch: {
    'tempVariable'(val) {
      if(val) {
        if(val.invest && val.sales) {
          this.form.techRate = ((val.invest / val.sales)*100).toFixed(2)
        }
      }

    },
    info: {
      immediate: true,
      handler (obj) {
        if(obj.projectYear) {
          this.getYearData(obj.projectYear)
          this.getList(obj.projectYear)
        }
      }
    },

  }
};
</script>
