<template>
  <div>
    <div style="display: flex;">
      <div :style="'width:' + (window.pageWidth - 200 - 110 - 25) + 'px;'">
        <el-table :data="customerOrg.contactPersonList" border :height="(window.pageHeight < 600 ? 100:window.pageHeight - 400)/2"
          size="small" highlight-current-row @row-click="rowClick" ref="customerOrg.contactPersonList">
          <el-table-column prop="displayName" label="姓名" min-width="70" align="center"/>
          <el-table-column prop="title" label="职务" min-width="70" align="center"/>
          <el-table-column prop="remark" label="备注" min-width="150" align="center"/>
          <el-table-column prop="creatorName" label="创建者" min-width="70" align="center" />
          <el-table-column prop="creationTime" label="创建时间" min-width="120" align="center">
            <template slot-scope="scope">
              <div v-if="scope.row.creationTime">
                {{ moment(scope.row.creationTime).format('yyyy-MM-DD HH:mm:ss') }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="lastModifierName" label="修改者" min-width="70" align="center"/>
          <el-table-column prop="lastModificationTime" label="修改时间" min-width="120" align="center">
            <template slot-scope="scope">
              <div v-if="scope.row.lastModificationTime">
                {{ moment(scope.row.lastModificationTime).format('yyyy-MM-DD HH:mm:ss') }}
              </div>
            </template>
          </el-table-column>
        </el-table>

        <el-table :data="customerOrg.contactMethodList" border :height="(window.pageHeight < 600 ? 100:window.pageHeight - 400)/2"
          size="small" highlight-current-row @row-click="rowClickMethod" ref="customerOrg.contactMethodList">
          <el-table-column prop="contactMethodType" label="类型" width="60" align="center">
            <template slot-scope="scope">
              <div>
                {{ scope.row.contactMethodType === "0" ? "手机" : "邮箱" }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="contactMethodValue" label="联系方式"  min-width="120" align="center"/>
          <el-table-column prop="creatorName" label="创建者" min-width="70" align="center" />
          <el-table-column prop="creationTime" label="创建时间" min-width="120" align="center">
            <template slot-scope="scope">
              <div v-if="scope.row.creationTime">
                {{ moment(scope.row.creationTime).format('yyyy-MM-DD HH:mm:ss') }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="lastModifierName" label="修改者" min-width="70" align="center"/>
          <el-table-column prop="lastModificationTime" label="修改时间" min-width="120" align="center">
            <template slot-scope="scope">
              <div v-if="scope.row.lastModificationTime">
                {{ moment(scope.row.lastModificationTime).format('yyyy-MM-DD HH:mm:ss') }}
              </div>              
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div style="margin-left: 10px; margin-top: 20px">
        <div v-show="checkPagePriv(pagePriv.privs,'新增联系人')" style="margin-top: 10px">
          <el-button type="primary" @click="add" class="commonbutton">新增联系人</el-button>
        </div>
        <div v-show="checkPagePriv(pagePriv.privs,'编辑联系人')" style="margin-top: 10px">
          <el-button type="success" @click="edit" class="commonbutton">编辑联系人</el-button>
        </div>
        <div v-show="checkPagePriv(pagePriv.privs,'删除联系人')" style="margin-top: 10px">
          <el-button type="danger" @click="del" class="commonbutton">删除联系人</el-button>
        </div>
      </div>
    </div>
    <!-- 联系人 -->
    <el-dialog :title="formTitle" :visible.sync="dialogContactPerson" width="800px" @close="closeDialogPerson">
      <el-form :model="form" ref="form" label-width="70px" :rules="rules" style="margin-top: -30px;">
        <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="contactMethodListEdit" 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>
      <span slot="footer" class="dialog-footer">
        <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>
      </span>
    </el-dialog>
  </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:["customerOrgId"],
  data() {
    return {
      pagePriv:{
        routeUrlorPageName:'customerOrg', //当前页面归属路由或归属页面权限名称
        privs:[] // 页面权限
      },     
      personId: "",
      form: {}, //联系人表单信息
      contactMethodListEdit:[],  //联系方式（可修改）
      formTitle: "新增",
      dialogContactPerson: false, //联系人弹窗 显示控制

      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))
  },

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

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

  methods: {
    moment,checkPagePriv,
    
    //获取联系人列表
    getContactPersonList(customerOrgId) {
      if(!customerOrgId){
        this.customerOrg.contactPersonList = [];
        this.customerOrg.contactMethodList = []
        return
      }
      getapi(
        `/api/app/contact-person/in-customer-org-id/${customerOrgId}`
      ).then((res) => {
        if(res.code != -1){
          this.customerOrg.contactPersonList = res.data;      
          if (res.data.length > 0) {
            this.getContactMethodList(res.data[0].id);
          } else {
            this.customerOrg.contactMethodList = [];
          }
        }
      });
    },

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

    //联系人 相关操作
    add() {
      //console.log("新增 addContactPerson");
      if (!this.customerOrgId) {
        this.$message.warning("没有体检单位信息");
        return;
      }
      this.form = { customerOrgId: this.customerOrgId };
      this.dialogContactPerson = true;
      this.formTitle = "新增";
      this.personId = "";
      this.customerOrg.contactMethodList = [];
      this.contactMethodListEdit = [];
    },

    edit() {
      //console.log("编辑 editContactPerson");
      console.log('this.customerOrgId',this.customerOrgId)
      if (!this.customerOrgId) {
        this.$message.warning("没有体检单位信息");
        return;
      } else if (!this.personId) {
        this.$message.warning("请先选择要编辑的联系人");
        return;
      }
      this.dialogContactPerson = true;
      this.formTitle = "编辑";
    },

    //删除联系人行
    del() {
      //console.log("删除 delContactPerson");
      if (!this.personId) {
        this.$message.warning("请先选择要编辑的联系人");
        return;
      }

      this.$confirm("此操作将永久删除该记录, 是否继续?", "提示", {
        confirmButtonText: "是",
        cancelButtonText: "否",
        type: "warning",
      }).then(() => {
        //console.log('{patientRegisterIds}',{patientRegisterIds})
        return deletapi(`/api/app/contact-person/${this.personId}`);
      }).then((res) => {
        if(res.code != -1)  {
          this.personId = "";

          this.getContactPersonList(this.customerOrg.customerOrgId);

          this.customerOrg.contactMethodList = [];
          console.log("操作成功！");
        }          
      }).catch((err) => {
        if (err == "cancel") {
          this.$message.info("已取消删除");
        }
      });
    },

    //删除联系方式行
    deleteRow(index) {
      this.$confirm("此操作确定后将永久删除该记录, 是否继续?", "提示", {
        confirmButtonText: "是",
        cancelButtonText: "否",
        type: "warning",
      }).then(() => {
        this.contactMethodListEdit.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);
        console.log("body", body);
        if (this.formTitle == "新增") {
          postapi("/api/app/contact-person", body)
            .then((res) => {
              //console.log('api/app/contact-person')
              if(res.code != -1){
                this.form.id = res.data.id;
                this.personId = res.data.id;
                this.formTitle = "编辑";
                return deletapi(`/api/app/contact-method/many/${this.personId}`);
              }              
            })
            .then((res) => {
              //console.log(`deletapi api/app/contact-method/${this.personId}`)
              if(res.code != -1){
                let contactMethod = []; //联系方式form表单数据
                this.contactMethodListEdit.forEach( item => {
                  contactMethod.push({
                    contactMethodValue: item.contactMethodValue,
                    contactMethodType: item.contactMethodType,
                    contactPersonId: this.personId,
                  });
                });
                if(contactMethod.length > 0){
                  return postapi("/api/app/contact-method/many", contactMethod);
                }else{
                  this.dialogContactPerson = false
                }
              }              
            })
            .then((res) => {
              //console.log('api/app/contact-method/many')
              //this.getContactPersonList(this.customerOrgId); //改成局部刷新
              if(res.code != -1){

                this.getContactMethodList(this.form.id)

                console.log("操作成功！");
                this.dialogContactPerson = false
              }              
            });
        } else {
          putapi(`/api/app/contact-person/${this.personId}`, body)
            .then((res) => {
              //console.log(`/api/app/contact-person/${this.personId}`)
              if(res.code != -1){
                return deletapi(`/api/app/contact-method/many/${this.personId}`);
              }              
            })
            .then((res) => {
              console.log(`deletapi api/app/contact-method/${this.personId}`);
              if(res.code != -1){
                let contactMethod = []; //联系方式form表单数据
                this.contactMethodListEdit.forEach((item, index) => {
                  contactMethod.push({
                    contactMethodValue: item.contactMethodValue,
                    contactMethodType: item.contactMethodType,
                    contactPersonId: this.personId,
                  });
                });
                if(contactMethod.length > 0){
                  return postapi("/api/app/contact-method/many", contactMethod);
                }else{
                  this.dialogContactPerson = false
                }
              }
             
            })
            .then((res) => {
              //console.log('api/app/contact-method/many')
              //this.getContactPersonList(this.customerOrgId); //改成局部刷新
              if(res.code != -1){
                
                this.getContactMethodList(this.form.id)
                console.log("操作成功！");
                this.dialogContactPerson = false
              }              
            });
        }        
      })
    },

    //新增或编辑后选中记录
    closeDialogPerson(){      
      let currentRow = {}
      let lfind = arrayExistObj(this.customerOrg.contactPersonList,'id',this.form.id)
      if(lfind > -1){
        objCopy(this.form,this.customerOrg.contactPersonList[lfind])
        currentRow = this.customerOrg.contactPersonList[lfind]        
      }else if(this.form.id){
        currentRow = deepCopy(this.form)
        lfind = this.customerOrg.contactPersonList.length        
        this.customerOrg.contactPersonList.push(currentRow)        
      }

      if(lfind > -1){
        setTimeout(() => { 
          this.$refs['customerOrg.contactPersonList'].setCurrentRow(currentRow)
        }, 100)
      }    
      
    },

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

    rowClick(row) {
      console.log("row", row);
      // console.log("rowClick");
      this.form = deepCopy(row);
      this.personId = row.id;
      this.getContactMethodList(row.id);
    },

    rowClickMethod(row) {
      //console.log("rowClickMethod");
    },
  },

  watch: {
    // 单位id未变时，强制刷新
    "dataTransOpts.refresh.contact_person.M": {
      // immediate: true,
      handler(newVal, oldVal) {
        console.log(`watch 联系人 newVal:${newVal} oldVal:${oldVal} customerOrgId: ${this.dataTransOpts.tableS.customer_org.id}`);
        this.getContactPersonList(this.dataTransOpts.tableS.customer_org.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';
.btnClass {
  width: 110px;
}



</style>
