<template>
  <div>
    <el-form :model="form" ref="form" label-width="70px" :rules="rules" style="margin-top: -10px;">
      <el-row>
        <el-col :span="12">
          <el-form-item prop="displayName" label="联系人">
            <el-input v-model="form.displayName" size="small"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="职务">
            <el-input v-model="form.title" size="small"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input type="textarea" v-model="form.remark" size="small" maxlength="50" show-word-limit></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="5">
          <el-form-item label="创建者">
            <el-input v-model="form.creatorName" disabled size="small"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="创建时间" label-width="80px" style="margin-left:-10px;">
            <el-date-picker v-model="form.creationTime" type="datetime" size="small" style="width: 100%" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="修改者">
            <el-input v-model="form.creatorName" disabled size="small"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="修改时间" label-width="80px" style="margin-left:-10px;">
            <el-date-picker v-model="form.lastModificationTime" type="datetime" size="small" style="width: 100%"
              disabled />
          </el-form-item>
        </el-col>
      </el-row>
      <el-table :data="contactMethodList" border height="300" row-key="id" size="small" highlight-current-row
        ref="contactMethod" style="margin-top: 20px;">
        <el-table-column prop="contactMethodType" label="类型" width="200">
          <template slot-scope="scope">
            <el-select v-model="scope.row.contactMethodType" size="small">
              <el-option v-for="item in Methodtypes" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="contactMethodValue" label="联系方式">
          <template slot-scope="scope">
            <el-input v-model="scope.row.contactMethodValue" required size="small" />
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="60" align="center">
          <template slot-scope="scope">
            <i class="el-icon-delete" @click="deleteRow(scope.$index)"
              style="font-size: 24px;color: red;cursor:pointer;"></i>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <div style="display: flex;justify-content: space-between;margin-top: 10px;">
      <div></div>
      <div>
        <el-button class="commonbutton" @click="dialogContactPerson = false">取 消</el-button>
        <el-button type="success" class="commonbutton" @click="addMethod">新增联系方式</el-button>
        <el-button type="primary" class="commonbutton" @click="submit('form')">确 定</el-button>
      </div>
    </div>

  </div>
</template>
<script>
import moment from "moment";
import { mapState } from "vuex";
import { getapi, postapi, putapi, deletapi } from "@/api/api";
import { getPagePriv, checkPagePriv, objCopy, deepCopy, arrayExistObj } from "../../utlis/proFunc";
export default {
  components: {},
  props: ["refFunc"],
  data() {
    return {
      pagePriv: {
        routeUrlorPageName: 'customerOrg', //当前页面归属路由或归属页面权限名称
        privs: [] // 页面权限
      },

      form: { //联系人表单信息
        id: "",
        customerOrgId:'',
        creationTime: null,
        lastModificationTime: null,
        creatorName: "",
        lastModifierName: "",
        displayName: "",
        title: "",
        remark: "",
      }, 
      formInit:{},
      contactMethodList: [],  //联系方式（可修改）


      Methodtypes: [
        //{ value: '',label: '所有订单状态' },
        { value: "0", label: "电话" },
        { value: "1", label: "邮箱" },
      ],

      rules: {
        displayName: [
          { required: true, message: "请输入名称", trigger: "blur" },
        ],
      },
    };
  },

  created() {
    //获取用户当前页面的权限
    let userPriv = window.sessionStorage.getItem('userPriv')
    if (userPriv) this.pagePriv.privs = deepCopy(getPagePriv(this.pagePriv.routeUrlorPageName))
    this.formInit = deepCopy(this.form)
  },

  //挂载完成
  mounted() {
    this.getFormData(this.dataTransOpts.tableS.contact_person.id)
  },

  computed: {
    ...mapState(["window", "customerOrg","dialogWin", "dataTransOpts"]),
  },

  methods: {
    moment, checkPagePriv,

    // 获取表单数据
    getFormData(id){
      if(!id){
        this.form = deepCopy(this.formInit)
        this.form.customerOrgId = this.dataTransOpts.tableS.customer_org.id
        this.contactMethodList = []
        return
      }
      getapi(`/api/app/contact-person/${id}`)
      .then(res =>{
        if(res.code != -1){
          this.form = deepCopy(res.data)
          this.getContactMethodList(res.data.id)
        }
      })
      
    },

    //获取联系方式列表
    //api/app/contact-method/in-contact-person-id?ContactPersonId=3a0c08ad-4304-138b-d9e6-a7338739dfc4' \
    getContactMethodList(ContactPersonId) {
      if (!ContactPersonId) {
        this.contactMethodList = []
        return
      }
      getapi("/api/app/contact-method/in-contact-person-id", {
        ContactPersonId,
      }).then(res => {
        //console.log('res.data',res.data)
        if(res.code != -1) this.contactMethodList = res.data;
      });
    },

    //删除联系方式行
    deleteRow(index) {
      this.$confirm("此操作确定后将永久删除该记录, 是否继续?", "提示", {
        confirmButtonText: "是",
        cancelButtonText: "否",
        type: "warning",
      }).then(() => {
        this.contactMethodList.splice(index, 1);
        //this.submit('form');
      }).catch((err) => {
        if (err == 'cancel') {
          this.$message.info("已取消删除");
        }
      });
    },

    //联系人信息提交
    submit(formName) {
      let body = {
        customerOrgId: "",
        displayName: "",
        title: "",
        remark: "",
      };
      this.$refs[formName].validate((valid, fields) => {
        if (!valid) {
          this.$message.warning(fields[Object.keys(fields)[0]][0].message);
          return false;
        }

        objCopy(this.form, body);
        let contactMethod = {
          contactPersonId: this.form.id,
          details:this.contactMethodList
        }

        console.log("body,contactMethod", body,contactMethod);

        if (!this.form.id) {
          postapi("/api/app/contact-person", body)
            .then((res) => {
              //console.log('api/app/contact-person')
              if (res.code != -1) {
                this.form = res.data                
                this.dataTransOpts.tableS.contact_person.id = res.data.id
                this.refFunc(['curChooseRow'],res.data)
                contactMethod.contactPersonId = res.data.id
                return postapi('/api/app/contactmethod/createmany',contactMethod);
              }
            })
            .then((res) => {
              //console.log('api/app/contact-method/many')
              if (res && res.code != -1) {
                console.log("操作成功！");
                this.dialogWin.ContactPersonEdit = false
              }
            });
        } else {
          putapi(`/api/app/contact-person/${this.form.id}`, body)
            .then((res) => {
              if (res.code != -1) {
                this.refFunc(['curChooseRow'],this.form)
                return postapi('/api/app/contactmethod/createmany',contactMethod);
              }
            })
            .then((res) => {
              //console.log('api/app/contact-method/many')
              //this.getContactPersonList(this.customerOrgId); //改成局部刷新
              if (res && res.code != -1) {
                console.log("操作成功！");
                this.dialogWin.ContactPersonEdit = false
              }
            });
        }
      })
    },

    //新增联系方式
    addMethod() {
      this.contactMethodList.push({
        contactMethodValue: "",
        contactMethodType: "0",
        contactPersonId: this.form.id,
      });
    },

  },

  watch: {
    // 单位id未变时，强制刷新
    "dataTransOpts.refresh.contact_person.S": {
      // immediate: true,
      handler(newVal, oldVal) {
        console.log(`watch 联系人 newVal:${newVal} oldVal:${oldVal} customerOrgId: ${this.dataTransOpts.tableS.contact_person.id}`);
        this.getFormData(this.dataTransOpts.tableS.contact_person.id)
      }
    },

    // 'customerOrgId' (newVal,oldVal){
    //   console.log('watch customerOrgId',newVal,oldVal)
    //   if(newVal != oldVal){
    //     this.personId = ''
    //   }
    // }
  },
};
</script>
<style scoped>
@import '../../assets/css/global_table.css';
@import '../../assets/css/global_input.css';
@import '../../assets/css/global_form.css';
@import '../../assets/css/global_dialog.css';

.btnClass {
  width: 110px;
}
</style>
