<template>
  <div>
    <xy-dialog ref="dialog" :is-show.sync="isShow" type="form"
      :title="type === 'add' ? `新增${typeName}记录` : `编辑${typeName}记录`" :form="form" :rules="rules" @submit="submit">
      <template v-slot:visitinfo>
        拜访信息
      </template>
      <template v-slot:date>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>到访日期：
          </div>
          <div class="xy-table-item-content">
            <el-date-picker style="width:300px" v-model="form.date" value-format="yyyy-MM-dd" type="date"
              placeholder="选择到访日期">
            </el-date-picker>
          </div>
        </div>
      </template>

      <template v-slot:end_date>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;"></span>结束日期：
          </div>
          <div class="xy-table-item-content">
            <el-date-picker style="width:300px" v-model="form.end_date" value-format="yyyy-MM-dd" type="date"
              placeholder="选择结束日期">
            </el-date-picker>
          </div>
        </div>
      </template>

      <template v-slot:time>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>到访时间：
          </div>
          <div class="xy-table-item-content">
            <el-time-picker
              v-model="form.time"
              format="HH:mm"
              value-format="HH:mm"
              :picker-options="{
                  start: '08:30',
                  step: '00:30',
                  end: '17:00'
                }"
              placeholder="选择到访时间">
            </el-time-picker>
          </div>
        </div>
      </template>
      <template v-slot:visit_time_id>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>到访时段：
          </div>
          <div class="xy-table-item-content">
            <el-radio-group v-model="form.visit_time_id" style="width:300px">
              <el-radio v-for="item in visitTimeList" :label="item.id">{{item.start_time}}-{{item.end_time}}</el-radio>
            </el-radio-group>
          </div>
        </div>
      </template>
      <template v-slot:visit_area_id>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>前往区域：
          </div>
          <div class="xy-table-item-content">
            <el-radio-group v-model="form.visit_area_id" style="width:300px" @change="changeVisitArea">
              <el-radio v-for="item in visitAreaList" :label="item.id">{{item.name}}</el-radio>
            </el-radio-group>
          </div>
        </div>
      </template>
      <template v-slot:reason v-if="visitType==1">
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;"></span>到访事由：
          </div>
          <div class="xy-table-item-content">
            <el-select v-model="form.reason" placeholder="请选择" style="width:300px">
              <el-option v-for="item in reasonList" :key="item.value" :label="item.value" :value="item.value">
              </el-option>
            </el-select>
          </div>
        </div>
      </template>
      <template v-slot:workRange v-if="visitType==2">
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;"></span>施工时段：
          </div>
          <div class="xy-table-item-content">
            <el-date-picker v-model="form.workRange" @change="changeworkrange" type="daterange" align="right" unlink-panels
              value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间">
            </el-date-picker>
          </div>
        </div>
      </template>

      <template v-slot:plate v-if="visitType==3">
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            车辆类型：
          </div>
          <div class="xy-table-item-content">
            <el-radio-group v-model="form.plate" style="width:300px">
              <el-radio v-for="item in parkAreaList" :key="item.value" :label="item.value">{{item.value}}</el-radio>
            </el-radio-group>
            <!-- <el-input v-model="form.plate" placeholder="请输入车牌号"></el-input> -->
          </div>
        </div>
      </template>
      <template v-slot:remark>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            备注：
          </div>
          <div class="xy-table-item-content">
            <el-input :autosize="{minRows:2}" style="width:300px" type="textarea" v-model="form.remark"
              placeholder="请输入备注" clearable></el-input>
          </div>
        </div>
      </template>
      <template v-slot:visitorinfo>
        <div class="xy-table-item">
          <div class="xy-table-item-content" style="width:400px">
            拜访人信息：
          </div>
        </div>
      </template>
      <template v-slot:name>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>姓名：
          </div>
          <div class="xy-table-item-content">
            <el-input v-model="form.name" placeholder="请输入姓名"></el-input>
          </div>
        </div>
      </template>
      <template v-slot:mobile>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>联系电话：
          </div>
          <div class="xy-table-item-content">
            <el-input v-model="form.mobile" placeholder="请输入联系电话"></el-input>
          </div>
        </div>
      </template>
      <template v-slot:credent>
        <div class="xy-table-item">
          <div class="xy-table-item-label">证件类型：
          </div>
          <div class="xy-table-item-content">
            <el-select v-model="form.credent" placeholder="请选择" style="width:100%">
              <el-option v-for="item in credentList" :key="item.id" :label="item.value" :value="item.id">
              </el-option>
            </el-select>
          </div>
        </div>
      </template>
      <template v-slot:idcard>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span v-if="visitType==2||visitType==3" style="color: red;font-weight: 600;padding-right: 4px;">*</span>证件号码：
          </div>
          <div class="xy-table-item-content">
            <el-input v-model="form.idcard" placeholder="请输入证件号码"></el-input>
          </div>
        </div>
      </template>
      <template v-slot:company_name>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
           <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>单位名称：
          </div>
          <div class="xy-table-item-content">
            <el-input v-model="form.company_name" placeholder="请输入单位名称"></el-input>
          </div>
        </div>
      </template>
      <!-- <template v-slot:cda v-if="visitType==1&&visitAreaText=='生产区'">
        <div class="xy-table-item">
          <div class="xy-table-item-label">
           <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>CDA编号：
          </div>
          <div class="xy-table-item-content">
            <el-input v-model="form.cda" placeholder="请输入CDA编号(如无注明原因)"></el-input>
          </div>
        </div>
      </template> -->

     <!-- <template v-slot:cars v-if="visitType==3">
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;"></span>到访车辆：
          </div>
          <div class="xy-table-item-content">
            <div v-for="(item,index) in form.cars">
              <el-input v-model="form.cars[index]" placeholder="请输入到访车辆"></el-input>
            </div>
          </div>
        </div>
      </template> -->

   <template v-slot:cars v-if="visitType==3">
      <div class="xy-table-item">
        <div class="xy-table-item-label">
          <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>到访车辆：
        </div>
        <div class="xy-table-item-content">
          <Button type="primary" icon="md-add" style="margin-bottom: 10px"
            @click="carsList.push({car:''})">新增到访车辆</Button>
          <xy-table style="width: 620px" :height="180" :is-page="false" :list="carsList"
            :table-item="carTable">
            <template v-slot:btns>
              <el-table-column label="操作" width="90" header-align="center" align="center">
                <template v-slot:default="scope">
                  <Button size="small" type="primary" ghost
                    @click="carsList.splice(scope.$index, 1)">删除</Button>
                </template>
              </el-table-column>
            </template>
          </xy-table>
        </div>
      </div>
    </template>
    <template v-slot:carsno v-else>
       <div class="xy-table-item">
         <div class="xy-table-item-label">
           <span style="color: red;font-weight: 600;padding-right: 4px;"></span>到访车辆：
         </div>
         <div class="xy-table-item-content">
           <Button type="primary" icon="md-add" style="margin-bottom: 10px"
             @click="carsList.push({car:''})">新增到访车辆</Button>
           <xy-table style="width: 620px" :height="180" :is-page="false" :list="carsList"
             :table-item="carTable">
             <template v-slot:btns>
               <el-table-column label="操作" width="90" header-align="center" align="center">
                 <template v-slot:default="scope">
                   <Button size="small" type="primary" ghost
                     @click="carsList.splice(scope.$index, 1)">删除</Button>
                 </template>
               </el-table-column>
             </template>
           </xy-table>
         </div>
       </div>
     </template>


      <template v-slot:follw_people v-if="visitType==1||visitType==2">
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;"></span>随访人员：
          </div>
          <div class="xy-table-item-content">
            <Button type="primary" icon="md-add" style="margin-bottom: 10px"
              @click="followList.push({ name:'',mobile:'',credent:1,idcard:'',credent_name:'身份证' })">新增随访人员</Button>

            <xy-table style="width: 620px" :height="260" :is-page="false" :list="followList"
              :table-item="followTable">
              <template v-slot:btns>
                <el-table-column label="操作" width="90" header-align="center" align="center">
                  <template v-slot:default="scope">
                    <Button size="small" type="primary" ghost
                      @click="followList.splice(scope.$index, 1)">删除</Button>
                  </template>
                </el-table-column>
              </template>
            </xy-table>
          </div>
        </div>
      </template>

      <!-- <template v-slot:long_time>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>长访客申请：
          </div>
          <div class="xy-table-item-content" style="width:620px">
            <el-radio-group v-model="form.long_time">
              <el-radio v-for="item in longList" :label="item.id">{{item.value}}</el-radio>
            </el-radio-group>
            <div v-if="form.long_time==1" style="display: inline-block;vertical-align: middle;margin-left:10px">
              <el-date-picker style="width:360px" @change="changelongrange" v-model="form.longrange" type="daterange" align="right" unlink-panels
                value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
              </el-date-picker>
            </div>
          </div>
        </div>
      </template> -->

      <template v-slot:visitorinfos v-if="visitType==1||visitType==2">
        <div class="xy-table-item">
          <div class="xy-table-item-content" style="width:400px">
            被访人信息：
          </div>
        </div>
      </template>

      <template v-slot:accept_admin_id v-if="visitType==1||visitType==2">
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>人员：
          </div>
          <div class="xy-table-item-content">
            <el-select filterable v-model="form.accept_admin_id" @change='changeAdmin1' placeholder="请选择" style="width:100%">
              <el-option v-for="item in adminList" :key="item.id"  :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </div>
        </div>
      </template>
      <!-- <template v-slot:visitorinfos1 v-if="visitAreaText=='生产区'">
        <div class="xy-table-item">
          <div class="xy-table-item-content" style="width:400px">
            陪同人信息：
          </div>
        </div>
      </template>
      <template v-slot:accompany_id v-if="visitAreaText=='生产区'">
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>人员：
          </div>
          <div class="xy-table-item-content">
            <el-select filterable v-model="form.accompany_id" @change='changeAdmin' placeholder="请选择" style="width:100%">
              <el-option v-for="item in adminList" :key="item.id"  :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </div>
        </div>
      </template> -->
      <template v-slot:accept_goods_admin_id v-if="visitType==3">
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>被访人：
          </div>
          <div class="xy-table-item-content">
            <el-select filterable v-model="form.accept_goods_admin_id" @change='changeGoods' placeholder="请选择" style="width:100%">
              <el-option v-for="item in adminList" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </div>
        </div>
      </template>


    </xy-dialog>


  </div>
</template>

<script>
  import {
    show,
    save
  } from "@/api/visit/record.js"
  import {
    getparameter
  } from "@/api/system/dictionary";
  import {
    getList as getTimeList
  } from '@/api/resource/visittime.js'
  import {
    getList as getAreaList
  } from '@/api/parameter/visitor.js'
  import {
    listCommonuser
  } from "@/api/common.js"
  export default {
    components: {},
    data() {
      return {
        isShow: false,
        type: 'add',
        id: '',
        visitType: "",
        typeName: '',
        visitAreaText:"",
        form: {
          // type: 1,
          visitinfo: "",
          date: "",
          end_date:'',
          time:'',
          visit_time_id: "",
          visit_area_id: "",
          workRange: "",
          reason: "",
          plate: "",
          remark: "",
          visitorinfo: "",
          name: "",
          mobile: "",
          credent: 1,
          idcard: "",
          company_name: "",
          // cda:'',
          cars: [],
          carsno:[],
          follw_people: [],
          long_time: 0,
          longrange: "",
          visitorinfos: "",
          accpet_department_id: "",
          accept_admin_id: "",
          visitorinfos1:'',
          accompany_id:'',
          accept_goods_admin_id: ""
        },
        followList:[],
        carsList:[],
        visitTimeList: [],
        visitAreaList: [],
        parkAreaList: [],
        reasonList: [],
        credentList: [{
            id: 1,
            value: "身份证"
          },
          {
            id: 2,
            value: "护照"
          },
        ],
        longList: [{
            id: 0,
            value: "否"
          },
          {
            id: 1,
            value: "是"
          },
        ],
        departmentList: [],
        adminList: [],
        carTable:[{
          label: "车牌号",
          prop: "car",
          // width: 200,
          customFn: (row, scope) => {
            return (<el-input type="text" placeholder = "请填写车牌号"
              v-model={row.car}>
              </el-input>
            )
          }
        }],
        followTable: [{
            label: "姓名",
            prop: "name",
            width: 200,
            customFn: (row, scope) => {
              return (<el-input type="text" placeholder = "请填写姓名"
                v-model={row.name}>
                </el-input>
              )
            }
          },
          {
            label: "联系电话",
            prop: "mobile",
            width: 200,
            customFn: (row, scope) => {
              return (<el-input type="text" placeholder = "请填写联系电话"
                v-model = {row.mobile} >
                </el-input>
              )
            }
          },
          {
            label: "证件类型",
            // width: 180,
            width: 200,
            customFn: (row) => {
              return (<el-select placeholder = "请选择证件类型"
                style = "width: 140px"
                value = {row.credent==1?'身份证':'护照'}
                on = {
                  {
                    ["change"]: (e) => (row.credent_name = e.value, row.credent = e.id),
                  }
                } > {
                  this.credentList.map((item, index) => {
                    return (<el-option
                      // v-for={item in types}
                      value = {
                        item
                      }
                      key = {
                        item.id
                      }
                      label = {
                        item.value
                      } >
                      </el-option>
                    )

                  })
                } </el-select>
              );
            },
          }, {
            label: "证件号码",
            prop: "idcard",
            width: 200,
            customFn: (row, scope) => {
              return (<el-input type="text" placeholder = "请填写证件号码"
                v-model = {row.idcard}>
                </el-input>
              )
            }
          }
        ],

        rules: {
          date: [{
            required: true,
            message: '请选择到访日期'
          }],
          visit_time_id: [{
            required: true,
            message: '请选择到访时段'
          }],
          visit_area_id: [{
            required: true,
            message: '请选择到访区域'
          }],
          plate: [{
            required: true,
            message: '请选择停车区域'
          }],
          name: [{
            required: true,
            message: '请输入姓名'
          }],
          mobile: [{
              required: true,
              message: "请填写联系电话",
            },
            {
              pattern: /^[1][3-9][\d]{9}/,
              message: "手机号格式错误",
            }
          ],
          company_name: [{
            required: true,
            message: '请输入单位名称'
          }],
          // cda:[{
          //   required: true,
          //   message: '请输入CDA编号'
          // }],
          // cars: [{
          //   required: true,
          //   message: '请输入车牌号'
          // }],
          // accompany_id: [{
          //   required: true,
          //   message: '请选择陪同人'
          // }],
          accept_admin_id: [{
            required: true,
            message: '请选被访人'
          }],
          accept_goods_admin_id: [{
            required: true,
            message: '请选择被访人'
          }]

        },
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        }
      }
    },
    created() {
      this.getLabel()
    },
    methods: {

      async getDetail() {
        const res = await show({
          id: this.id
        })
        this.form = {
          visitinfo: "",
          date: res?.date,
          end_date: res?.end_date,
          time:res?.time,
          visit_time_id: res?.visit_time_id,
          visit_area_id: res?.visit_area_id,
          workRange: res.work_start_time?[res.work_start_time,res.work_end_time]:"",
          reason: res?.reason,
          plate: res?.plate,
          remark: res?.remark,
          visitorinfo: "",
          name: res?.name,
          mobile: res?.mobile,
          credent: res?.credent,
          idcard: res?.idcard,
          company_name: res?.company_name,
          // cda:res?.cda,
          cars:[],
          carsno: [],
          follw_people: res?.follw_people,
          long_time: res?.long_time,
          longrange: res.start_date?[res.start_date,res.end_date]:"",
          visitorinfos: "",
          accpet_department_id: res?.accpet_department_id,
          accept_admin_id: res?.accept_admin_id,
          visitorinfos1:'',
          accompany_id:res?.accompany_id,
          accept_goods_admin_id: res?parseInt(res.accept_goods_admin_id):''
        }
        this.followList = res?.follw_people
        for(var k of res?.cars){
          this.carsList.push({car:k})
        }
        this.visitAreaText = res?.visit_area.name
        console.log(this.followList,this.carsList)
      },
      async getLabel() {
        const res = await getTimeList()
        this.visitTimeList = res.data
        const resarea = await getAreaList()
        this.visitAreaList = resarea.data
        const resuser = await listCommonuser({page:1,page_size:999,show_all:1})
        this.adminList = resuser.data

        const reason = await getparameter({
          number: "reasonList",
        });
        this.reasonList = reason?.detail;
        const park = await getparameter({
          number: "parkArea",
        });
        this.parkAreaList = park?.detail;

      },
      changeVisitArea(val){
        console.log(val)
        this.visitAreaList.map(item=>{
          if(item.id==val){
            this.visitAreaText = item.name
          }
        })
        console.log(this.visitAreaText)
      },
      changelongrange(val){
        this.form.start_date = val[0]
        this.form.end_date = val[1]
      },
      changeworkrange(val){
        this.form.work_start_time = val[0]
        this.form.work_end_time = val[1]
      },
      changeAdmin(item){
        if(item){
          this.adminList.map(e=>{
            if(e.id==item){
              this.form.accompany_id = e.id
            }
          })

        }
      },
      changeAdmin1(item){
        if(item){
          this.adminList.map(e=>{
            if(e.id==item){
              this.form.accept_admin_id = e.id
              this.form.accpet_department_id = e.department_id
              this.form.accompany_id = e.id
              // if(this.visitAreaText=='非生产区'){
              //   this.form.accompany_id = e.id
              // }
            }
          })

        }
      },
      changeGoods(item){
        if(item){
          this.adminList.map(e=>{
            if(e.id==item){
              this.form.accept_admin_id = e.id
              this.form.accept_goods_admin_id = e.id
              this.form.accpet_department_id = e.department_id
              if(this.visitAreaText=='非生产区'){
                this.form.accompany_id = e.id
              }
            }
          })

        }
      },
      submit() {
        let that = this
        const isIdcardRequired = that.visitType == 2 || that.visitType == 3
        const hasIdcard = !!that.form.idcard

        // 施工人员、物流司机必须填写证件号
        if (isIdcardRequired && !hasIdcard) {
          this.$successMessage('证件号码不能为空', '', 'warning')
          return
        }

        // 只要填写了证件号就进行格式校验（普通访客、施工、物流统一生效）
        if (hasIdcard && that.form.credent == 1) {
          const regtest = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
          if (!regtest.test(that.form.idcard)) {
            this.$successMessage('身份证格式错误', '', 'warning')
            return
          }
        }
        if (hasIdcard && that.form.credent == 2) {
          const regtest = /^([a-zA-z]|[0-9]){5,17}$/
          if (!regtest.test(that.form.idcard)) {
            this.$successMessage('护照格式错误', '', 'warning')
            return
          }
        }
        that.form.follw_people = that.followList
        let _car = []
        for(var k of that.carsList){
          _car.push(k.car)
        }
        this.form.cars = _car
        console.log("this.form.cars",this.form.cars)
        // return
        if(this.visitType==3){
          this.form.accept_admin_id = this.form.accept_goods_admin_id
        }
        if (this.type === 'editor') {
          this.form.id = this.id
        }else{
          this.form.id = ""
        }
        // return
        save({
          ...that.form
        }).then(res => {
          this.$successMessage(this.type, this.typeName)
          this.isShow = false
          this.$emit('refresh')
        })
      }
    },
    watch: {
      isShow(newVal) {
        if (newVal) {
          console.log("this.visitType",this.visitType)
          this.form.type = this.visitType
          this.form.audit_status = 1
          if (this.type === 'editor') {
            this.getDetail()
          }
        } else {
          this.id = ''
          this.type = ''
          this.visitType = 1
          this.followList = []
          this.carsList = []
          this.visitAreaText=''
          this.$refs['dialog'].reset()
        }
      },
      visitType(val) {
        if (val) {
          this.typeName = val == 1 ? '普通访客' : (val == 2 ? '施工人员' : (val == 3 ? '物流司机' : ''))
        }
      }

    }

  }
</script>

<style scoped lang="scss">
  .xy-table-item-label {
    width: 180px !important;
  }

  .xy-table-item-content {
    width: 100%
  }

  .img__delete {
    transform: scale(0.8, 0.8);

    position: absolute;
    top: 4px;
    right: 4px;
  }
  .carsitem{
    width:450px;margin-bottom:10px;margin-bottom: 10px;display: flex;align-items: center;justify-content: space-between;
  }
  .carsitem Button{
    margin-left:10px
  }
</style>
