<template>
  <el-container>
    <el-header>
      <el-steps
        :active="active"
        style="width: 100%;margin-top:16px"
        :align-center="true"
        finish-status="success"
      >
        <el-step
          v-for="(item, index) of stepTitle"
          :key="index"
          :title="item"
          style="50%"
          @click="handleStep(index)"
        >
        </el-step>
      </el-steps>
    </el-header>
    <!--基本信息!-->
    <el-main class="nopadding" v-show="active === 0">
      <el-form
        ref="dialogForm"
        :model="form"
        :rules="rules"
        :disabled="mode == 'show'"
        label-width="100px"
        style="margin: 40px 40px 40px 40px"
      >
        <el-row>
          <el-col :md="8" :sm="12" :xs="24" >
            <el-form-item label="来访事由" prop="purpose">
              <el-select v-model="form.purpose" placeholder="选择来访事由">
                <el-option
                  v-for="item in purposeoptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="8" :sm="12" :xs="24">
            <el-form-item label="来访概述" prop="name">
              <el-input v-model="form.name" type="text" clearable></el-input>
            </el-form-item>
          </el-col>

          <el-col :md="8" :sm="12" :xs="24">
            <el-form-item label="来访时间" prop="visit_time">
              <el-date-picker
                v-model="form.visit_time"
                type="datetime"
                placeholder="选择来访时间"
                :default-time="defaultTime_start"
              />
            </el-form-item>
          </el-col>

          <el-col :md="8" :sm="12" :xs="24">
            <el-form-item label="离开时间">
              <el-date-picker
                :default-time="defaultTime"
                v-model="form.leave_time"
                type="datetime"
                placeholder="选择离开时间"
              />
            </el-form-item>
          </el-col>

          <el-col :md="8" :sm="12" :xs="24">
            <el-form-item label="来访单位" prop="company">
              <el-input v-model="form.company" type="text" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :md="8" :sm="24" :xs="24">
            <el-form-item label="来访级别" prop="level">
              <el-radio-group v-model="form.level">
                <el-radio-button label="10">一般</el-radio-button>
                <el-radio-button label="20">重要</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :md="8" :sm="12" :xs="24">
            <el-form-item label="来访人数" prop="count_people">
              <el-input-number
                v-model="form.count_people"
                :min="0"
                :max="32767"
                controls-position="right"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :md="16" :sm="12" :xs="24">
            <el-form-item label="来访详述" prop="description">
              <el-input
                v-model="form.description"
                type="text"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :md="8" :sm="24" :xs="24">
            <el-form-item label="接待人">
              <span style="display:flex">
                <el-input readonly v-model="form.receptionist_name"></el-input>
                <ehsUserSelect :multiple="false" @submit="getReceptionist"/>
                </span>
            </el-form-item>
          </el-col>
          <el-col :md="24" :sm="12" :xs="24" style="position: relative;" v-if="form.purpose==50">
						<span style="color:red;position: absolute;top: 8px;left: 18px;">*</span>
						<el-form-item label="车辆照片">
							<sc-upload-multiple v-model="fileurl2" @imagesDel="imagesDel" @imagesChange="imagesChange" draggable :limit="9" tip="最多上传9个文件,单个文件不要超过10M,请上传图像格式文件"></sc-upload-multiple>
					    </el-form-item>
					</el-col>
        </el-row>
      </el-form>
      <div style="margin-top:20px;text-align:center">
        <el-button style="margin-top: 20px"
           @click="handleNextStep"
           :loading="isSaving" 
           :disabled="isSaving"
           type="primary">
           下一步
          </el-button>
      </div>
    </el-main>

    <!--选择人员!-->
    <el-main class="nopadding" v-show="active === 1">
      <div class="left-panel">
        <el-button type="primary" icon="el-icon-plus" @click="add"></el-button>
      </div>
      <scTable
        ref="table"
        :data="peoplelist"
        row-key="id"
        height='auto'
        stripe
         hideDo
         hidePagination
      >
      <el-table-column label="#" type="expand">
              <template #default="scope">
                <el-descriptions :column="3" style="margin-left:70px">
                  <el-descriptions-item label="来源地:">{{ scope.row.come_place }}</el-descriptions-item>
                  <el-descriptions-item label="是否重要访客:">
                    <el-space v-if="scope.row.is_main == true">是</el-space>
                    <el-space v-else>否</el-space>
                  </el-descriptions-item>
                </el-descriptions>
              </template>
            </el-table-column>
        <el-table-column
          label="#"
          fixed="left"
          type="index"
          width="50"
        ></el-table-column>
        <el-table-column
          label="访客姓名"
          prop="visitor_.name"
        ></el-table-column>
        <el-table-column
          label="访客手机号"
          prop="visitor_.phone"
        ></el-table-column>
        <el-table-column
          label="访客身份证号"
          prop="visitor_.id_number"
        ></el-table-column>
        <el-table-column label="是否重要访客" prop="is_main">
          <template #default="scope"
            ><el-space v-if="scope.row.is_main == true">是</el-space>
            <el-space v-else>否</el-space>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="create_time"></el-table-column>
        <el-table-column label="操作" fixed="right" align="left" width="170">
          <template #default="scope">
            <el-button-group>
              <el-button
                text
                type="primary"
                size="small"
                @click="table_del(scope.row)"
                >删除</el-button
              >
            </el-button-group>
          </template>
        </el-table-column>
      </scTable>
      <!-- 新增人员 -->
      <el-dialog v-model="dialogpeople" draggable title="创建来访人员">
        <el-form
          ref="formpeople"
          :model="formpeople"
          :rules="peopleRules"
          :disabled="mode === 'show'"
          label-width="120px"
        >
          <el-row>
            <el-col :md="12" :sm="12" :xs="24">
              <el-form-item label="访客" prop="visitor">
                <el-select
                  style="width:100%"
                  v-model="formpeople.visitor"
                  placeholder="选择访客"
                >
                  <el-option
                    v-for="item in visitoroptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <!-- <el-col :md="12" :sm="12" :xs="24">
              <el-form-item label="返乡时间" prop="return_date">
                <el-date-picker
                  style="width:100%"
                  v-model="formpeople.return_date"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="选择返乡时间"
                />
              </el-form-item>
            </el-col>
            <el-col :md="12" :sm="12" :xs="24">
              <el-form-item label="核酸时间" prop="test_date">
                <el-date-picker
                  style="width:100%"
                  v-model="formpeople.test_date"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="选择核酸时间"
                />
              </el-form-item>
            </el-col> -->
            <el-col :md="12" :sm="12" :xs="24">
              <el-form-item label="来源地" prop="come_place">
                <sc-address :Address="formpeople.come_place" @selectedAddress="selectedAddress"></sc-address>
              </el-form-item>
            </el-col>
            <!-- <el-col :md="12" :sm="12" :xs="24">
              <el-form-item label="行程轨迹" prop="trip_desc">
                <el-input v-model="formpeople.trip_desc" type="text" clearable></el-input>
              </el-form-item>
            </el-col> -->
            <el-col :md="12" :sm="12" :xs="24">
              <el-form-item label="详细地址" prop="come_place_detail">
                <el-input v-model="formpeople.come_place_detail" type="text" clearable></el-input>
              </el-form-item>
            </el-col>
            <!-- <el-col :md="12" :sm="12" :xs="24">
              <el-form-item label="管控措施" prop="measure">
                <el-select v-model="formpeople.measure" style="width:100%" placeholder="选择来访事由">
                  <el-option
                    v-for="item in measureOptions"
                    :key="item"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
            </el-col> -->
            <el-col :md="12" :sm="12" :xs="24">
              <el-form-item label="是否主访客" prop="is_main">
                <el-radio-group v-model="formpeople.is_main">
                  <el-radio-button label="true">是</el-radio-button>
                  <el-radio-button label="false">否</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <!-- <el-col :md="12" :sm="12" :xs="24">
              <el-form-item label="是否报备" prop="is_reported">
                <el-radio-group v-model="formpeople.is_reported">
                  <el-radio-button label="true">是</el-radio-button>
                  <el-radio-button label="false">否</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :md="12" :sm="12" :xs="24">
							<el-form-item label="健康码" prop="health_code">
								<sc-upload v-model="formpeople.health_code" :modelValue="formpeople.health_code" title="健康码"></sc-upload>
							</el-form-item>
						</el-col>
            <el-col :md="12" :sm="12" :xs="24">
							<el-form-item label="行程码" prop="travel_code">
								<sc-upload v-model="formpeople.travel_code" :modelValue="formpeople.travel_code" title="行程码"></sc-upload>
							</el-form-item>
						</el-col>
            <el-col :md="12" :sm="12" :xs="24">
							<el-form-item label="核酸报告" prop="test_report">
								<sc-upload v-model="formpeople.test_report" :modelValue="formpeople.test_report" title="核酸报告"></sc-upload>
							</el-form-item>
						</el-col> -->
          </el-row>
        </el-form>
        <template #footer>
          <el-button @click="dialogpeople = false">取 消</el-button>
          <el-button type="primary" :loading="isSaving" @click="submitpeople">确 定</el-button>
        </template>
      </el-dialog>
      <div style="margin-top:20px;text-align:center">
          <el-button @click="handleLastStep"
              style="margin-right:4px">上一步</el-button
            >
            <span v-for=" item in initform.transitions" :key="item.id">
          <el-button
            :loading="isSaving" 
            :disabled="isSaving" 
            @click="submitticket(item.id)"
            style="margin-right:4px" type="primary"
          >{{item.name}}</el-button>
          </span>
          <el-button @click="submitOut" type="warning">退出</el-button>
      </div>
    </el-main>
  </el-container>
</template>
<style scoped>
.left-panel{
 margin:10px
}
.clearfix {
  font-size: 20px;
}

.box-card p {
  line-height: 20px;
}
.content {
  margin-top: 10px;
}
.stepSuc:hover {
  cursor: pointer;
}
.stepErr:hover {
  cursor: not-allowed;
}
</style>
<script>
  import { genTree } from "@/utils/verificate";
  import imgUpload from "@/components/scUpload/multiple.vue";
  import scAddress from "@/components/scAddress/SelectAddress.vue";

  const defaultformworker = {
    duty: "",
    rcertificates: [],
    rpj: "",
  };
  export default {
    name: "vistoradd",
    components:{
      scAddress,
      imgUpload
    },
    data() {
      return {
        fileurl2: "",
        measureOptions: ['集中隔离','居家隔离','居家健康检测','排除风险'],
        active: 0,
        stepSuc: [0],
        form: {
          purpose:10, 
          level:10,
          leave_time:'',
          vehicle_photos:[]
        },
        defaultTime_start:new Date(2000, 1, 1, 10, 0, 0),
        defaultTime:new Date(2000, 1, 1, 18, 0, 0),
        stepTitle: ["基本信息", "选择访客"],
        receptionistoptions: [],
        purposeoptions: [
          { id: 2, name: "售后服务" },
          { id: 4, name: "业务洽谈" },
          { id: 10, name: "参观" },
          { id: 20, name: "拜访" },
          { id: 30, name: "面试" },
          { id: 40, name: "开会" },
          { id: 50, name: "拉送货" },
          { id: 60, name: "其他" },
        ],
        search: {
          keyword: null,
        },
        come_place:'',
        dialog: {
          save: false,
          permission: false,
        },
        isSaving:false,
        apiObj: this.$API.vm.visit.list,
        query: {},
        selection: [],
        dialogpeople: false,
        formpeople: {
          id: "",
          visit: "",
          visitor: '',
          // return_date: '',
          come_place: '',
          come_place_detail:'',
          // trip_desc: '',
          // test_date:'',
          // measure: '',
          // health_code: '',
          // travel_code: '',
          // test_report: '',
          is_main: false,
          // is_reported: true,
        },
        rules: { 
          purpose: [{ required: true, message: "请输入" }],
          name: [{ required: true, message: "来访概述" }],
          visit_time: [{ required: true, message: "请输入" }],
          leave_time: [{ required: true, message: "请输入" }],
          receptionist: [{ required: true, message: "请输入" }],
          level: [{ required: true, message: "请输入" }],
          vehicle_photos:[{required: true, message: "请上传"}]
        },
        peopleRules:{
          visitor: [{ required: true, message: "请选择来访人员" }],
          return_date: [{ required: true, message: "请选择返乡日期" }],
          come_place: [{ required: true, message: "请填写来源地" }],
          come_place_detail: [{ required: true, message: "请填写来源地详细地址" }],
          trip_desc: [{ required: true, message: "请填写行程轨迹" }],
          test_date: [{ required: true, message: "请选择核酸日期" }],
          measure: [{ required: true, message: "请选择管控措施" }],
          health_code: [{ required: true, message: "请长传健康码截图" }],
          travel_code: [{ required: true, message: "请上传行程码截图" }],
          test_report: [{ required: true, message: "请上传核酸报告" }],
        },
        visitoroptions: [],
        peoplelist: [],
        initform:[],
        ticket:{},
      };
    },
    mounted() {
      this.visitid = this.$route.query.visitid; //作业ID
      this.isSaving = false;
      if(this.visitid){
        this.getRpj();
        this.getpeoplelistlist();
      }
      this.getvisitorlist();
    },
    methods: {
      imagesDel(index){
				//合并新增的图片Ids
				this.form.vehicle_photos.splice(index,1)
				//console.log(this.form.create_imgs)
			},
      imagesChange(data){
				// debugger;
				// console.log(data)
				//合并新增的图片Ids
				if(this.form.vehicle_photos){
					this.form.vehicle_photos = this.form.vehicle_photos.concat(data);
				}else{
					this.form.vehicle_photos = data;
				}
			},


      selectedAddress(data){
        // debugger;
        console.log(data)
        this.formpeople.come_place=data;
      },
      //访问项目基本信息
      getRpj() {
        this.$API.vm.visit.read.req(this.visitid).then((res) => {
          this.form = res;
          let imgsLset =[];
          if(res.vehicle_photos_.length>0){
            for(let i=0;i<res.vehicle_photos_.length;i++){
              imgsLset.push(res.vehicle_photos_[i].path)
            }
            this.fileurl2 =imgsLset.join(",");
          }
        });
      },
      getReceptionist(data) {
        // 子组件调用父组件的方法并传参
        this.form.receptionist=data.id;
        this.form.receptionist_name=data.name
      },
      //接待人
      //渲染工单提交按钮
      getInit(){
        this.$API.wf.workflow.initkey.req('visit').then((res) => {
          this.initform = res;
          
        });
      },
      handleStep(val) {
        //点击步骤条
        if (this.stepSuc.includes(val) === true) {
          this.active = val;
        }
      },
      //组件点击上一步
      handleLastStep() {
        if (--this.active === 0) {
          this.active = 0;
        }
      },
      //组件点击下一步
      handleNextStep() {
        debugger;
        console.log(this.form)
        if (this.active == 0) {
          this.$refs.dialogForm.validate(async (valid) => {
            if (valid) {
              this.isSaving = true;
              if(this.visitid){
                this.$API.vm.visit.update
                .req(this.visitid, this.form)
                .then((res) => {
                  this.$message.success("基本信息更新成功");
                  this.getInit();
                  this.active = 1;
                  this.isSaving = false;
                }).catch(()=>{
                  this.isSaving = false;
                })
              }else{
                this.$API.vm.visit.create.req(this.form).then(res=>{
                  this.visitid = res.id;
                  this.$message.success("项目创建成功");
                  this.getInit();
                  this.active = 1;
                  this.isSaving = false;
                }).catch(()=>{
                  this.isSaving = false;
                })
              }
            }
          });
        } else {
          this.active = 1;
        }
        // this.stepSuc.push(++this.active)
      },
      //退出界面
      submitOut() {
        this.$router.push({
          name: "visit",
          query: {},
        });
      },
      //添加
      add() {
        this.dialogpeople = true;
      },

      //项目访客人员
      getpeoplelistlist() {
        this.$API.vm.people.list
          .req({ visit: this.visitid, page: 0 })
          .then((res) => {
            this.peoplelist = res;
          });
      },

      //我的访客
      getvisitorlist() {
        this.$API.vm.visitor.list.req({ page: 0 }).then((res) => {
          this.visitoroptions = res;
        });
      },
      //表单提交方法
      submitpeople() {
        let that = this;
        that.formpeople.visit = this.visitid;
        let addressObj = that.formpeople.come_place;
        let addressStr = '';
        that.formpeople.come_place = '';
        for(let key in addressObj){
          addressStr =addressStr+addressObj[key];
        }
        that.formpeople.come_place = addressStr;
        // debugger;
        console.log(addressStr)
        that.$refs.formpeople.validate((valid) => {
          if (valid) {
            that.isSaveing = true;
            that.$API.vm.people.create
            .req(that.formpeople)
            .then((res) => {
              that.$message.success("创建成功");
              that.dialogpeople = false;
              that.isSaveing = false;
              this.getpeoplelistlist();
              return res;
            })
            .catch((err) => {
              that.isSaveing = false;
              return err;
            });
          }else{
              return false;
            }
        });
      },
      //删除访客信息
      table_del(row) {
        this.$API.vm.people.delete
          .req(row.id)
          .then((res) => {
            this.$message.success("访客删除成功");
            this.getpeoplelistlist();
            return res;
          })
          .catch((err) => {
            return err;
          });
      },
      //提交工单
      submitticket(id){
        this.ticket={};
        this.isSaving = true;
        this.ticket.title = this.form.name;
        this.ticket.workflow=this.initform.workflow;
        this.ticket.ticket_data={visit:this.visitid,name:this.form.name};
        this.ticket.transition=id;

        if(this.form.ticket!= null&&this.form.ticket!= undefined){
            this.$API.wf.ticket.ticketHandle.req(this.form.ticket,this.ticket).then((res) => {
              this.isSaving=false
              this.$message.success("提交成功");
              this.$router.push({
                name: "visit",
                query: {},
              });
            }).catch(e=>{this.isSaving=false});
          }else{
            this.$API.wf.ticket.create.req(this.ticket).then((res) => {
              this.isSaving=false
              this.$message.success("提交成功");
              this.$router.push({
                name: "visit",
                query: {},
              });
            }).catch(e=>{this.isSaving=false});
          }
      }
    },
  };
</script>