<template>
  <div>
    <el-button size="mini" :disabled="!tool.checkAuth($route.name,'update') || !data.disabled || data.status === '已失败'"  @click="editBtn" :type="!tool.checkAuth($route.name,'update') || !data.disabled || data.status === '已失败'? '':'primary'">编 辑</el-button>
    <el-drawer
        title="编辑项目商机"
        :visible.sync="dialogFormVisible"
        size="700px"
        direction="rtl"
        :show-close="false"
        append-to-body
        @close="onClose">
      <div class="drawer__panel">
        <el-row :gutter="20">
          <el-form :model="form" :rules="rules" ref="form" label-width="125px" label-position="right" size="mini">
            <el-col :span="24">
              <el-form-item label="项目名称:" prop="projectname">
                <el-input v-model="form.projectname" placeholder="请输入项目名称" :disabled="data.putFlag !== 0"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="项目类型:" prop="projecttype">
                <el-select v-model="form.projecttype" placeholder="请选择项目类型" size="mini">
                  <el-option
                      v-for="(item,index) in projectType()"
                      :key="index"
                      :label="item.value"
                      :value="item.value">
                    <span style="float: left">{{ item.value }}</span>
                    <span style="float: right; color: #8492a6; font-size: 12px">{{ item.remarks?item.remarks:'暂无描述' }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="项目等级:" prop="grade">
                <el-select v-model="form.grade" placeholder="请选择项目等级" size="mini">
                  <el-option
                      v-for="item in projectLead()"
                      :key="item.value"
                      :label="item.value"
                      :value="item.value">
                    <span style="float: left">{{ item.value }}</span>
                    <span style="float: right; color: #8492a6; font-size: 12px">{{ item.remarks?item.remarks:'暂无描述' }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="省市县:" prop="province">
                <el-cascader
                    :disabled="data.putFlag !== 0"
                    style="width:100%"
                    v-model="form.province"
                    :options="basicData.data().areaData"
                    @change="cascaderChange" clearable>
                </el-cascader>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="详细地址:" prop="address">
                <el-input v-model="form.address" placeholder="请输入详细地址" :disabled="data.putFlag !== 0"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="项目规模:" prop="scale">
                <el-input v-model="form.scale" placeholder="请输入建筑面积(㎡)/吨位(t)"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="项目预算(元):" prop="budgetary">
                <el-input type="number" v-model="form.budgetary" placeholder="项目预算"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="总投资额(百万):" prop="budgetary">
                <el-input type="number" v-model="form.totalinvestment" placeholder="总投资额"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item  label="造价(百万):" prop="budgetary">
                <el-input type="number" v-model="form.costofconstruction" placeholder="造价"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="预计开工时间:" prop="begdate_due">
                <el-date-picker
                    style="width: 100%"
                    v-model="form.begdate_due"
                    type="month"
                    placeholder="选择月"
                    :picker-options="pickerOptions"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="预计完工时间:" prop="enddate_due">
                <el-date-picker
                    style="width: 100%"
                    v-model="form.enddate_due"
                    type="month"
                    placeholder="选择月"
                    :picker-options="pickerOptions"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="预计签约时间:" prop="signdate_due">
                <el-date-picker
                    style="width: 100%"
                    v-model="form.signdate_due"
                    type="month"
                    placeholder="选择月份"
                    @change="timeChange">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="预计签约金额(元):" prop="signamount_due">
                <el-input v-model="form.signamount_due" placeholder="请输入预计签约金额" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="领域:" prop="tradefield">
                <el-select v-model="form.tradefield" placeholder="请选择领域">
                  <el-option
                      v-for="item in tradefieldSelect"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="品牌:" prop="sa_brandid">
                <el-select v-model="form.sa_brandid" placeholder="请选择品牌">
                  <el-option
                      v-for="item in brandSelect"
                      :key="item.sa_brandid"
                      :label="item.brandname"
                      :value="item.sa_brandid">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

          </el-form>
        </el-row>
      </div>
      <div class="fixed__btn__panel">
        <el-button size="small" @click="dialogFormVisible = false" class="normal-btn-width inline-16">取 消</el-button>
        <duplicateCheck :data="form"></duplicateCheck>
        <el-button size="small" type="warning" @click="onSave" class="normal-btn-width">保 存</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import duplicateCheck from "@/HDrpManagement/projectChange/components/duplicateCheck";
export default {
  name: "add",
  inject:['enterpriseList','projectType','projectLead','projectPanl'],
  components:{duplicateCheck},
  props:['data','btnType'],
  data(){
    var begdateTime = (rule,value,callback) =>{
      console.log(value,this.form.enddate_due)
      if (this.form.enddate_due !== ''){
        if (value > this.form.enddate_due){
          callback(new Error('预计开工时间不能晚于预计完工时间'))
        }else {
          callback();
        }
      }else {
        callback();
      }
    }
    var enddateTime = (rule,value,callback) =>{
      if (this.form.begdate_due !== ''){
        if (value < this.form.begdate_due){
          callback(new Error('预计完工时间不能早于预计开工时间'))
        }else {
          callback();
        }
      }else {
        callback();
      }
    }
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        }
      },
      dialogFormVisible:false,
      projectAddress:[],
      disabled:false,
      userInfo:JSON.parse(window.sessionStorage.getItem('userInfo')),
      addChange:false,
      checkResults:'',
      form:{
        sa_projectid:0,
        projectname:"",
        projectnum:"",
        address:"",//可选
        grade:"",//可选
        budgetary:"",//可选
        remarks:"",//可选
        projecttype:"",//可选
        sa_projstagetempid:"",//可选
        signdate_due:"",//可选
        scale:"",//可选
        signamount_due:"",//可选
        province:"",
        city:"",
        county:"",
        totalinvestment:'', //总投资额
        costofconstruction:'', //造价
        begdate_due:'', //预计开工时间
        enddate_due:'',  //预计完工时间
        sa_brandid:"",
        value:[],
        tradefield:''
      },
      brandSelect:[],
      tradefieldSelect:[],
      rules:{
        projectname:[
          { required: true, message: '输入项目名称', trigger: 'blur'},
        ],
        /*projectnum:[
          { required: true, message: '输入项目编号', trigger: 'blur'}
        ],*/
        projecttype:[
          { required: true, message: '请选择项目类型', trigger: 'change'}
        ],
        sys_enterpriseid:[
          { required: true, message: '请选择企业', trigger: 'blur'},
        ],
        /*sa_projstagetempid:[
          { required: true, message: '请选择当前项目模板', trigger: 'blur'}
        ],*/
        province:[
          { required: true, message: '请选择省市县', trigger: 'change'}
        ],
        tradefield:[
          { required: true, message: '请选择领域', trigger: 'change'}
        ],
        sa_brandid:[
          { required: false, message: '请选择品牌', trigger: 'change'}
        ],
        begdate_due:[
          { required: false, validator: begdateTime, trigger: 'change' }
        ],
        enddate_due:[
          { required: false, validator: enddateTime, trigger: 'change' }
        ],
      }
    }
  },
  watch:{
    mainData(val) {
      if (this.data.leader.length !== 0){
        if (JSON.parse(window.sessionStorage.getItem('userInfo')).userid === this.data.leader[0].userid){
          this.disabled = false
        }else {
          this.disabled = true
        }
      }
      console.log("权限结果",this.disabled)
    }
  },
  methods:{
    /*省市县*/
    cascaderChange (val) {
      this.form = Object.assign({},this.form,{city:val[1],county:val[2]})
    },
    editBtn () {
      this.dialogFormVisible = true
      this.form = Object.assign({},this.form,this.data)
      this.form.province = [this.form.province,this.form.city,this.form.county]
      /*this.form.grade = parseInt(this.form.grade)*/
      if (this.form.brandname === ''){
        this.form.sa_brandid = ''
      }
      /*this.form.tradefields = JSON.parse(this.form.tradefields)*/

      /*this.form.budgetary = this.form.budgetary !== 0 ? this.tool.formatAmount(this.form.budgetary,2):'' || ''
      this.form.totalinvestment  ? this.form.totalinvestment = this.tool.formatAmount(this.form.totalinvestment,2):this.form.totalinvestment = ''
      this.form.costofconstruction  ? this.form.costofconstruction = this.tool.formatAmount(this.form.costofconstruction,2):this.form.costofconstruction = ''
      this.form.signamount_due  ? this.form.signamount_due = this.tool.formatAmount(this.form.signamount_due,2):this.form.signamount_due = ''*/

    },
    /*自动查重判断*/
    duplicateCheck(){
      this.$refs.form.validate(async (valid) => {
        if (!valid) return false
        const res = await this.$api.requested({
          "id": 20221208184202,
          "content": {
            "projectname":this.form.projectname,
            "address":this.form.address,
            "sa_projectid":this.form.sa_projectid
          },
        })

        if (res.data.length !== 0){
          console.log("重复")
        }
        this.checkResults = res.data.length
        this.onSave()
      })
    },
    onSave(){
      if (this.checkResults === ''){
        this.duplicateCheck()
      }else {
        if (this.checkResults !== 0){
          this.$confirm('该项目疑似重复，是否确认保存项目?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.onSubmit()
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消保存'
            });
          });
        }else {
          this.onSubmit()
        }
      }
    },
    onSubmit(){
      if (this.form.signdate_due !== ''){
        const data = new Date(this.form.signdate_due)
        if (data.getMonth() +1 < 10){
          this.form.signdate_due = data.getFullYear() + '-0' + (data.getMonth() + 1)
        }else {
          this.form.signdate_due = data.getFullYear() + '-' + (data.getMonth() + 1)
        }
      }else {
        this.form.signdate_due = ''
      }
      if (this.form.begdate_due !== ''){
        const data = new Date(this.form.begdate_due)
        if (data.getMonth() +1 < 10){
          this.form.begdate_due = data.getFullYear() + '-0' + (data.getMonth() + 1)
        }else {
          this.form.begdate_due = data.getFullYear() + '-' + (data.getMonth() + 1)
        }
      }else {
        this.form.begdate_due = ''
      }
      if (this.form.enddate_due !== ''){
        const data = new Date(this.form.enddate_due)
        if (data.getMonth() +1 < 10){
          this.form.enddate_due = data.getFullYear() + '-0' + (data.getMonth() + 1)
        }else {
          this.form.enddate_due = data.getFullYear() + '-' + (data.getMonth() + 1)
        }
      }else {
        this.form.enddate_due = ''
      }

      /*this.form.tradefields[0] = this.form.tradefields
      console.log(this.form,'form')*/
      this.$refs['form'].validate(async (valid) => {
        if (!valid) return false
        this.form.province = this.form.province[0]
        const res = await this.$api.requested({
          "id": "20221020144202",
          "version":1,
          "content": this.form
        })
        this.tool.showMessage(res,()=>{
          if (this.checkResults === 0){
            this.$emit('onSuccess')
            this.$refs['form'].resetFields();
            this.dialogFormVisible = false
            this.addChange = false
            this.checkResults = ''
          }else {
            this.setTag(this.form.sa_projectid)
          }

        })
      })
    },
    async setTag(id) {
      const res = await this.$api.requested({
        "id": 20220929090901,
        "content": {
          "ownertable": "sa_project",
          "ownerid": id,
          "datatag": [
            "疑似重复",
          ]
        }
      })
      this.$emit('onSuccess')
      this.$refs['form'].resetFields();
      this.dialogFormVisible = false
      this.checkResults = ''
    },
    timeChange(e) {
      if(!e) {
        this.form.signdate_due = ''
      }
      let result = this.changeTimeFormat(e.getTime())
 
      this.form.signdate_due = result
    },
    changeTimeFormat(time) {
      var date = new Date(time);
      var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
      var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      return date.getFullYear() + "-" + month + "-" + currentDate
    },
    onClose(){
      this.dialogFormVisible = false
    },
    /*获取品牌*/
    async queryBrand(){
      const res = await this.$api.requested({
        content: {
          isExport: 0,
          pageNumber: 1,
          pageSize: 20,
          where: {
            condition: "",
            tablefilter: {}
          }
        },
        id: 20220922085103
      })
      this.brandSelect = res.data
    },
    /*获取领域*/
    queryTradefield(){
      this.$store.dispatch('optiontypeselect','tradefield').then(res=>{
        this.tradefieldSelect = res.data
      })
    }
  },
  mounted() {
    this.queryBrand()
    this.queryTradefield()
  }
}
</script>

<style scoped>
/deep/.el-select {
  height: 28px !important;
  width: 100%;
}
/deep/.el-input__inner {
  height: 28px !important;
}
</style>