<template>
  <div>
    <el-form :model="paramForm" :rules="rules" ref="formRef" label-width="90px" size="small" class="demo-ruleForm">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="任务ID">
            <el-input :disabled="true" v-model="paramForm.taskId" placeholder="请输入" style="width: 100%"></el-input>
          </el-form-item>

          <el-form-item label="关联客户" prop="customerName">
            <el-input v-model="paramForm.customerName" readonly @focus="customerData"  placeholder="请选择" style="width: 100%">
               <i slot="suffix" @click="customerData" class="el-input__icon el-icon-arrow-down"></i>
            </el-input>
          </el-form-item>

          <el-form-item label="事项类型" prop="itemType">
            <common-select :dictType="'Crm_Event_Type'"  v-model="paramForm.itemType" @handleButton="setItemType" style="width: 100%"></common-select>
          </el-form-item>

        </el-col>


        <el-col :span="12">
          <el-form-item label="任务来源" prop="taskSource">
            <common-select :dictType="'Crm_Task_Source'" v-model="paramForm.taskSource" :disabled="isEdit" style="width: 100%"></common-select>
          </el-form-item>
          <el-form-item label="截止时间" prop="taskRequestDate">
            <el-date-picker v-model="paramForm.taskRequestDate" :picker-options="pickerOptions" type="date"
              placeholder="选择日期时间"  value-format="yyyy-MM-dd" style="width: 100%">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="紧要程度" prop="emergencyDegree">
            <common-select :dictType="'Crm_Import_Level'" v-model="paramForm.emergencyDegree" @handleButton="setEmergencyDegree" style="width: 100%"></common-select>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="任务描述" prop="taskContent">
            <el-input v-model="paramForm.taskContent" maxlength="300" show-word-limit type="textarea"
              placeholder="请输入" style="width: 100%"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="负责人员" prop="taskUser">
            <aws-org v-model="taskUserdata" :isDialog="true" :ismuti="false" :sid="sid"   @change="responsible(taskUserdata)"
              :editable="openType =='view'? false : true" ref="awsorgRefTwo" :users="taskUserdata" @submit="responsible " style="width: 100%">
            </aws-org>
          </el-form-item>
          <el-form-item label="关联项目">
            <el-select v-model="paramForm.projectCode" :disabled="pCodeEnble|| !canEdit" placeholder="请选择" @visible-change="projectData" clearable ref="models" filterable style="width: 100%">
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="协同人员" prop="informerParamList" ref="infoList">
           <aws-org v-model="personnelData" :isDialog="true" :sid="sid" :editable="openType =='view'? false : true"               @change="personnelDataChange"
              ref="awsorgRef" @submit="coordination" :users="personnelData" style="width: 100%">
            </aws-org>
          </el-form-item>
          <el-form-item label="关联拜访报告">
            <el-select  v-model="paramForm.visitReportCode" :disabled="visitDisable" placeholder="请选择" @visible-change="visitData" clearable ref="model" filterable style="width: 100%">
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
     <!-- <el-form-item style="margin-bottom: 0;text-align: center" label-width="0px">
        <el-button @click="submitForm('draft')" type="warning">保存</el-button>
        <el-button v-if="hideedit" @click="submitForm('dealing')" type="primary">提交</el-button>
        <el-button @click="visible=false" type="info">取消</el-button>
      </el-form-item>-->
    </el-form>
    <dialog-customer ref="digCostomRef" :isDialog="true" @setCustValue="setCustValue"></dialog-customer>
    <project-list ref="projectDialog" :isDialog="true" @setCustValue="paramrow"></project-list>
    <vivst-list ref="visitDialog" :isDialog="true" @setCustValue="visitrow"></vivst-list>
  </div>
</template>

<script>
  import commonSelect from './common-select.vue'//引用字典下拉框组件
  import commonSelectList from '../common/commonSelectList.js'
  import projectList from './projectList.vue'//引用项目dialog组件
  import vivstList from './vivstList.vue'//引用拜访dialog组件
  export default {
    name: "task-form",
    components: {
      commonSelect,
      projectList,
      vivstList
    },
    props: {
      cusdisabled: { //客户名称是否禁用taskContent
        type: Boolean,
        default: false
      },
      pCodeEnble: { //项目编码是否禁用编辑
        type: Boolean,
        default: false
      },
      preservationData: { //保存按钮区分是否调接口还是保存到dom缓存数据
        type: Boolean,
        default: false
      },
      hideedit:{//是否隐藏编辑按钮
        type: Boolean,
        default: false
      },
      visitDisable:{//是否禁用拜访编码
        type: Boolean,
        default: false
      },
      modelId:{
        type: Number,
        default: 3104
      },
    },
    mounted: function() {

    },
    computed: {
      sid() {
        return this.$common.getUrlParams('sid');
      }
    },
    created() {
      this.addStutas()
    },
    methods: {
      //区分模块并赋默认值
      defaultTaskSource(){
        switch(this.modelId){
          //项目
          case 3101:
            this.paramForm.taskSource = 'project'
          break;
          //拜访报告
          case 3102:
            this.paramForm.taskSource = 'visit'
          break;
          //工作报告
          case 3103:
            this.paramForm.taskSource = 'work'
          break;
          //任务
          case 3104:
            this.paramForm.taskSource = 'add'
            this.isEdit = false;
          break;
        }
      },
      //协同人员修改
      personnelDataChange() {
        if (this.personnelData && this.paramForm.informerParamList) {
          if (this.paramForm.informerParamList.length > 0) {
            this.paramForm.informerParamList =
              this.paramForm.informerParamList.filter((item) => {
                for (let row of this.personnelData) {
                  if (item.userId === row.uid) {
                    return true;
                  }
                }
              });
          }
        }
      },
      //获取客户数据
      customerData() {
        this.$refs.digCostomRef.visible = true;
      },
      //编辑任务数据
      editDetail(row,i) {
            var form={};
                form=Object.assign(form,row);
            this.paramForm = form;
            this.paramForm.tableid=i;
            // 封装协同人员
            var personnelData = [];
            for (var i = 0; i < form.informerParamList.length; i++) {
              var person = {
                uid: form.informerParamList[i].userId,
                id: form.informerParamList[i].userId,
                email: form.informerParamList[i].email,
                name: form.informerParamList[i].userName,
              };
              personnelData.push(person);
            }
            this.personnelData=personnelData;
            var taskUserdata = [
              {
                uid: form.taskUserId,
                id: form.taskUserId,
                name: form.taskUser,
              },
            ];
            this.taskUserdata=taskUserdata;
            this.resetAws(taskUserdata,personnelData);
      },
      setItemType(val){
        //由于新增需要自己遍历字典拿到对应的key值显示 所以需要循环
        this.eventType.forEach((impor, index) => {
          debugger;
          if (impor.vaule === val) {
            debugger;
            this.paramForm.itemTypeKey = impor.key;
          }
        });
      },
      setEmergencyDegree(val){
        this.importdata.forEach((item, index) => {
          if (item.vaule === val) {
            this.paramForm.emergencyDegreeKey = item.key;
          }
        });
      },
      //选择项目编号后的回调赋值
      paramrow(data) {
        this.paramForm.projectCode=data.projectCode
        this.paramForm.relatedProjectsNumber = data.id
      },
      //选择拜访编号后的回调赋值id获取
      visitrow(data) {
        debugger;
        if (!data.visitReportCode) {
          data.visitReportCode = data.visitCode
        }
        this.paramForm.visitReportCode=data.visitReportCode;
        this.paramForm.visitReportNumber = data.id;
      },

    //获取 AWS 负责人名字以及id
    responsible(data) {
      console.log("获取 AWS 负责人 data===========>", data);
      if (data && data.length > 0) {
        this.taskUserdata = data[0];
        this.paramForm.taskUser = data[0].name;
        this.paramForm.taskUserId = data[0].uid;
        } else {
        this.paramForm.taskUser = "";
        this.paramForm.taskUserId = "";
      }
    },
    //获取 AWS 获取协同人员信息
    coordination(data) {
      console.log("获取 AWS 获取协同人员信息===========>", data);
      var that = this;
      this.paramForm.informerParamList = [];
      var deleteIndex = -1;
      for (var i = 0; i < this.personnelData.length; i++) {
        this.paramForm.informerParamList.push({
          userId: this.personnelData[i].uid,
          userName: this.personnelData[i].name,
          email: this.personnelData[i].email,
        });
        if (deleteIndex > -1) {
          this.$refs.awsorgRef.closeItemTag(deleteIndex);
          this.personnelData.splice(deleteIndex, 1);
          this.$refs.awsorgRef.reset(this.personnelData);
        }
      }
      if(this.paramForm.informerParamList!=null&&this.paramForm.informerParamList!='[]'){
        this.$refs['infoList'].clearValidate()//清除单个验证
      }
    },
      //获取提交的通用字典
      async addStutas() {
         this.eventType = await commonSelectList.initDictDataGet(this, "Crm_Event_Type");
         this.importdata =await commonSelectList.initDictDataGet(this, "Crm_Import_Level");
      },
      //获取关联客户名字以及id
      setCustValue(row) {
        this.paramForm.customerName = row.customerFullName
        this.paramForm.customerId = row.customerNo
      },
      //触发关联客户组件
      customer() {
        this.$refs.digCostomRef.visible = true;
      },
      open () {
         if(this.$route.query.projprojectObjectObj){
           let obj = this.$route.query.projectObj;
           this.paramrow(obj);
           this.paramForm.customerName = obj.customer;
           this.paramForm.customerId = obj.customerId;
           this.canEdit = false;
         }
          //默认给操作类型赋值
          this.defaultTaskSource()
      },
      //时间选择
      tiemDate() {
        console.log(this.paramForm.taskRequestDate)
      },
      // 调用关联项目dialog组件
      projectData() {
        this.$refs.projectDialog.visible = true;
        this.$refs.projectDialog.openTitle = "项目报告";
        this.$refs.models.blur()
      },
      //调用关联拜访dialog组件
      visitData() {
        this.$refs.visitDialog.visible = true;
        this.$refs.model.blur()
      },
      setParamForm(){
        let  userNamesStr="";
        if(this.paramForm.informerParamList!=null && this.paramForm.informerParamList.length>0){
          this.paramForm.informerParamList.forEach((info, index) => {
            userNamesStr+=info.userName+",";
          });
          this.paramForm.userNamesStr=userNamesStr;
        }
        this.paramForm.taskRequestDateFormat=this.paramForm.taskRequestDate.substring(0,10);
        return this.paramForm;
      },
      //关闭弹窗
      handleClose() {
        if (this.$refs['formRef']) {
          this.$refs['formRef'].clearValidate();
        }
        for (var item in this.paramForm) {
          this.paramForm[item] = '';
        }

        this.paramForm.modelId=this.modelId;
        this.paramForm.status="draft";
        this.paramForm.statusKey="草稿";

        this.taskUserdata = [];
        this.personnelData = [];
        this.resetAws(this.taskUserdata, this.personnelData);
        this.visible = false;
      },
      resetAws(taskUserList, personList) {
        this.$refs.awsorgRef.reset(personList)
        this.$refs.awsorgRefTwo.reset(taskUserList)
      }
    },
    data() {
      return {
        //选择时间大于当前时间设置
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7;
          }
        },
        isEdit:true, //任务来源是否可编辑
        visible: false,
        canEdit: true, //客户名称，管理项目是否可编辑
        openTitle: '',
        openType: '',
        draft: '',
        dealing: '',
        options: [],
        taskUserdata: [],
        enidinfo: {},
        modeData:[],
        method: [],
        stutasData: [],
        eventType: [],
        importdata:[],
        TypeStatus:[],
        reviewStatus:[],
        personnelData: [],
        paramForm: {
          userId:'',
          customerId: '',
          customerName: '',
          emergencyDegree: '',
          emergencyDegreeKey:'',
          notifyContent: '',
          extId: '',
          informerParamList:[],
          modelId: this.modelId || 3104,
          notifyWayId: "dingding",
          modelType: "",
          parentTaskId: "",
          recordStatus: "",
          projectCode:'',
          relatedProjectsNumber: "",
          status: "draft",
          statusKey:"草稿",
          taskContent: '',
          taskCompletedDate: '',
          itemType:'',
          itemTypeKey:'',
          taskContent: '',
          taskId: '',
          taskLookOver: 0,
          taskRequestDate: '',
          taskSource: '',
          taskTitle: '',
          taskUser: '',
          taskUserId: '',
          visitReportCode:'',
          visitReportNumber: '',
        },
       rules: {
         //紧要程度
         emergencyDegree: [
           {
             required: true,
             message: '请选择',
             trigger: 'change',
           }
         ],
         //任务来源
         taskSource: [
           {
             required: true,
             message: '请选择',
             trigger: 'change'
           }
         ],
         //截止时间
         taskRequestDate: [
           {
             required: true,
             message: '请选择',
             trigger: 'change'
           }
         ],
         //负责人员
         taskUser: [
           {
             required: true,
             message: '请选择',
             trigger: 'change'
           }
         ],
         //协同人员
         informerParamList: [
           {
             required: true,
             message: '请选择',
             trigger: 'blur'
           }
         ],
         //任务描述
         taskContent: [
           {
             required: true,
             message: '请填写',
             trigger: 'blur'
           }
         ],
         //事项类型
         itemType: [
           {
             required: true,
             message: '请选择',
             trigger: 'change'
           }
         ],
       }
      }
    }
  }
</script>

<style type="text/css" lang="scss">

</style>
