<template>
  <div>
    <el-button size="mini" :disabled="disabled" v-if="tool.checkAuth($route.name,'update') " @click="editBtn" :type="disabled ? '':'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">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="项目预算(万元):" prop="budgetary">
                <el-input v-model="form.budgetary" placeholder="项目预算"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="项目规模:" prop="scale">
                <el-input v-model="form.scale" placeholder="请输入项目规模"></el-input>
              </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="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">
                  </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="signdate_due">
                <el-date-picker
                    style="width: 100%"
                    v-model="form.signdate_due"
                    type="date"
                    placeholder="选择月份"
                    @change="timeChange">
                </el-date-picker>
              </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(){
    return {
      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":"",
      },
      rules:{
        projectname:[
          { required: true, message: '输入项目名称', trigger: 'blur'},
        ],
        projectnum:[
          { required: true, message: '输入项目编号', trigger: 'blur'}
        ],
        projecttype:[
          { required: true, message: '请选择项目类型', trigger: 'blur'}
        ],
        sys_enterpriseid:[
          { required: true, message: '请选择企业', trigger: 'blur'},
        ],
        sa_projstagetempid:[
          { required: true, message: '请选择当前项目模板', trigger: 'blur'}
        ],
        province:[
          { required: true, message: '请选择项目地址', trigger: 'blur'}
        ]
      }
    }
  },
  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
      console.log(this.data,"res项目商机数据")
      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)*/
      console.log(this.form,"项目商机内容")
    },
    /*自动查重判断*/
    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
          },
        })
        console.log(res,"查重结果")
        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(){
      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
    }
  },
}
</script>

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