<template>
  <div class="app-container form-box" style="padding:20px">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-card class="top15 ">
        <div class="table-card">
          <el-row type="flex" justify="space-around">
            <el-col :span="8"></el-col>
            <el-col :span="8" class="formTitle"> {{title}}</el-col>
            <el-col :span="8" style="text-align: right;padding-right: 20px;">
              <BottomBtn :accessId="accessId" :isAuthorised="isAuthorised" @onConfirm="handleBtTottom" />
            </el-col>
          </el-row>
        </div>
        <div class="table-card table-card-content">
          <el-row>
            <el-col :span="24">
              <el-form-item label="单号" prop="applyNo" v-if="$route.query.id">
                <el-input size="small" v-model="form.applyNo" disabled placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="公司名称">
                <CommonName str="cn" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目名称" prop="projectName">
                <el-input size="small" :disabled="disabled" v-model="form.projectName" placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="申请人">
                <CommonName str="an" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请部门">
                <CommonName str="apt" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="预计费用" prop="amount" v-if="$route.query.typeStr === 'daily'" :rules="[{ message: '请输入正整数', required: false, trigger: 'blur'},{ validator: VerifyFunc.newNumber }]">
                <el-input size="small" v-model="form.amount" :disabled="disabled" placeholder="请输入">
                  <span slot="suffix">元</span>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="申请事由" prop="reason">
                <el-input type="textarea" :disabled="disabled" size="small" :rows="5" v-model="form.reason" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注信息" prop="remark">
                <el-input type="textarea" :disabled="disabled" size="small" :rows="5" v-model="form.remark" placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="附件">
                <UploadFile @onUploadFile="handleUpload" :files="fileList" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="['business'].includes($route.query.typeStr)">
            <el-col :span="24">
              <el-form-item label="行程信息">
                <div class="rode-box">
                  <div class="item-box" v-for="(item,index) in form.expenseApplyTrips" :key="index">
                    <div class="box-tt">
                      <span>行程{{index + 1}}
                        <span v-if="item.tripPartners.length">
                          <el-button icon="el-icon-user" type="text" :disabled="disabled" @click="handleShowFw(item.tripPartners,index)">查看{{item.tripPartners.length}}位同行人</el-button>
                        </span>
                      </span>
                      <span class="delicon" v-if="form.expenseApplyTrips.length >1" @click="handleDelRode(index)"><i class="el-icon-delete"></i></span>
                    </div>
                    <div class="box-content">
                      <el-row class="rw-bt">
                        <el-col :span="12">
                          <el-form-item label="行程时间" :prop="`expenseApplyTrips.${index}.time`" :rules="[{ message: '请选择', required: true, trigger: 'change'}]">
                            <el-date-picker class="wd100" :disabled="disabled" v-model="item.time" size="small" @change="handleTimeChange($event,index)" type="daterange" align="right" start-placeholder="开始日期" end-placeholder="结束日期">
                            </el-date-picker>
                          </el-form-item>
                        </el-col>
                        <el-col :span="6">
                          <el-form-item label="出差天数" :prop="`expenseApplyTrips.${index}.tripDay`" :rules="[{ message: '请输入', required: true, trigger: 'blur'},{ validator: VerifyFunc.newNumber }]">
                            <el-input-number class="wd100" :disabled="disabled" :controls="false" size="small" v-model="item.tripDay" placeholder="请输入" />
                          </el-form-item>
                        </el-col>
                        <el-col :span="6">
                          <el-form-item label="出差类型" :prop="`expenseApplyTrips.${index}.tripType`" :rules="[{ message: '请选择', required: true, trigger: 'change'}]">
                            <el-select v-model="item.tripType" :disabled="disabled" class="wd100" size="small" placeholder="请选择" filterable>
                              <el-option v-for="it of tripTypeList" :key="it.id" :value="it.value" :label="it.label"></el-option>
                            </el-select>
                          </el-form-item>
                        </el-col>
                      </el-row>
                      <el-row class="rw-bt">
                        <el-col :span="12">
                          <el-form-item label="出发地" :prop="`expenseApplyTrips.${index}.departureLocation`" :rules="[{ message: '请选择', required: true, trigger: 'change'}]">
                            <el-cascader size="small" :disabled="disabled" filterable clearable :props="defaultProps" class="wd100" v-model="item.departureLocation" :options="$store.getters.areaTree"></el-cascader>
                          </el-form-item>
                        </el-col>
                        <el-col :span="12">
                          <el-form-item label="目的地" :prop="`expenseApplyTrips.${index}.destinationLocation`" :rules="[{ message: '请选择', required: true, trigger: 'change'}]">
                            <el-cascader size="small" :disabled="disabled" filterable clearable :props="defaultProps" class="wd100" v-model="item.destinationLocation" :options="$store.getters.areaTree"></el-cascader>
                          </el-form-item>
                        </el-col>
                      </el-row>
                      <el-row class="rw-bt">
                        <el-col :span="24">
                          <el-form-item label="行程时间" class="op0">
                            <el-button icon="el-icon-plus" :disabled="disabled" @click="handleAddFw(index)" size="small" plain type="primary"> 添加同行人</el-button>
                          </el-form-item>
                        </el-col>
                      </el-row>
                      <el-row>
                        <el-col :span="24">
                          <div class="account-box">
                            <el-form-item :prop="`expenseApplyTrips.${index}.amount`" :rules="[{ message: '请输入正整数', required: false, trigger: 'blur'},{ validator: VerifyFunc.newNumber }]">
                              <span style="margin-right:10px">行程{{index+1}}预计费用</span> <span>￥<el-input-number v-model="item.amount" :disabled="disabled" style="width:100px" :controls="false"></el-input-number></span>
                            </el-form-item>
                          </div>
                        </el-col>
                      </el-row>
                    </div>
                  </div>
                </div>
                <div class="btn-box" @click="handleAddRode" v-if="!disabled">
                  <i class="el-icon-plus" style="color:#1890ff"></i> <span style="color:#1890ff">添加行程信息</span>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-card>
    </el-form>
    <el-image-viewer v-if="dialogVisible" :zIndex="9999" :on-close="closeImgViewer" :url-list="imgList" />
    <!-- 添加同行人 -->
    <Together :isOpen="tgIsOpen" :selectUserIds="selectUserIds" @onCancel="handleTgCl" @onConfirm="handleTgCm" @onList="handleInit" />
    <!-- 展示同行人列表 -->
    <List :isOpen="lsIsOpen" :userList="userList" :selectIds="selectIds" @onCancel="handleLsCl" @onConfirm="handleLsCm" />
    <!-- 打印信息 -->
    <el-dialog :visible.sync="showPrintPage" width='1200px' custom-class="print-dialog" style="height: 98vh;overflow-y: auto;">
      <div style="text-align: right;margin-bottom:10px;">
        <el-button @click="PrintRow" type='primary' size='mini' plain>确认打印</el-button>
      </div>
      <div id="printMe" ref="print" class="print-main">
        <print-html :infoForm='form' :dialogTitle="`${this.$route.query.typeStr==='daily' ? '日常申请单' : '出差申请单'}`" :tasks="tasks" :tripTypeList="tripTypeList" :userList="userList" />
      </div>
    </el-dialog>
    <!-- 审批流程信息 -->
    <FlowDialog ref="FlowDialog" :isOpen="showFlow" @onCancel="showFlow = false" @onSetId="handleSetApprovalId" @onTasks="handleTasks" :processInstanceId="form.processInstanceId" />
  </div>
</template>

<script>
import { debounce } from 'lodash'
import dayjs from "dayjs";
import { listData } from "@/api/system/dict/data";
import { createExpenseApply, getExpenseApply } from "@/api/bs/expenseApply";
import VerifyFunc from "@/utils/verity";
import isBetween from 'dayjs/plugin/isBetween';
dayjs.extend(isBetween)


export default {
  name: 'supplierTb',
  components: {
    printHtml: () => import('./printHtml'),
    FilePreview: () => import('@/components/FilePreview'),
    CommonName: () => import('@/components/CommonName'),
    FlowDialog: () => import('@/components/FlowDialog'),
    BottomBtn: () => import('@/components/BottomBtn'),
    UploadFile: () => import('@/components/UploadFile'),
    Together: () => import('../../../components/Together'),
    List: () => import('../../../components/TogetherList'),
    // printHtml: () => import('./printHtml'),
  },
  created() {
    if (this.$route.query.id) {
      this.handleInitForm(this.$route.query.id)
    }
    this.handleInitList()
  },
  watch: {
    fileList: {
      immediate: true,
      deep: true,
      handler(val) {
        if (val.length >= 1) {
          this.hideUpload = true
        } else {
          this.hideUpload = false
        }
      }
    }
  },
  computed: {
    disabled() {
      return !['add', 'edit'].includes(this.$route.query.flag)
    },
    title() {
      return this.$route.query.title
    },
    isShow() {

    },
  },
  data() {
    return {
      isAuthorised: false,
      accessId: null,
      tasks: {},
      showFlow: false,
      showPrintPage: false,
      selectUserIds: [],
      VerifyFunc,
      defaultProps: {
        children: "children",
        label: "name",
        value: 'id',
        checkStrictly: false
      },
      areaTree: [],
      previewFile: false,
      fileUrl: null,
      mode: null,
      selectIds: [],
      lsIsOpen: false,
      tgIsOpen: false,
      addressList: [],
      tripTypeList: [],
      pdfName: null,
      isPdf: false,
      imgType: '.jpeg, .jpg, .png, .pdf',
      fileList: [],
      hideUpload: false,
      imgList: [], //当前图片src数组
      dialogVisible: false,
      prviewUrl: null,
      form: {
        amount: undefined,
        applyNo: null,
        projectName: null,
        reason: null,
        remark: null,
        expenseApplyTrips: [
          {
            time: [],
            startTime: null,
            endTime: null,
            departureLocation: null,
            destinationLocation: null,
            tripDay: undefined,
            tripType: null,
            tripPartners: [], // 出差同行人
            amount: undefined
          }
        ]
      },
      // 表单校验
      rules: {
        reason: [{ required: true, message: "请输入", trigger: "blur" }],
      },
      userList: [],
      index: 0
    }
  },
  methods: {
    handleSetApprovalId(id) {
      this.accessId = id
    },
    handleUpload(list) {
      this.fileList = list
    },
    handleBtTottom(val) {
      if (val === 0 || val === 1) {
        this.submitForm(val)
      } else if (val == 2) {
        this.showPrintPage = true
      } else {
        this.showFlow = true
      }
    },
    handleTasks(tasks) {
      this.tasks = tasks
    },
    PrintRow: debounce(function () { //确认打印档案
      this.$print(this.$refs.print)
    }, 200),
    handlePrint() {
      this.showPrintPage = true
    },
    handleLoop(array) {
      array.forEach(el => {
        if (el.children && !el.children.length) {
          delete el.children
        } else {
          this.handleLoop(el.children)
        }
      });
    },
    handleInitList() {
      listData({
        pageNo: 1,
        pageSize: 50,
        dictType: 'bs_trip_type',
      }).then((res) => {
        this.tripTypeList = res.data.list || []
      })
    },
    handleTimeChange(val, index) {
      let trips = this.form.expenseApplyTrips
      if (trips.length && val && val.length) {
        // 判断行程时间是否在已经有的时间范围内
        let start1 = dayjs(val[0]);
        let end1 = dayjs(val[1]);
        let range1 = { start: start1, end: end1 };
        for (let i = 0; i < trips.length; i++) {
          let start2 = dayjs(trips[i].time[0]);
          let end2 = dayjs(trips[i].time[1]);
          let range2 = { start: start2, end: end2 };
          if (index !== i && range1.start.isBefore(range2.end) && range2.start.isBefore(range1.end)
          ) {
            this.$set(this.form.expenseApplyTrips[index], 'time', null)
            return this.$modal.msgWarning(`行程时间范围与行程${i + 1}时间范围冲突！`)
          }
        }
      }
      let startTime = val && val.length && dayjs(val[0]).format('YYYY/MM/DD 00:00:00')
      let endTime = val && val.length && dayjs(val[1]).format('YYYY/MM/DD 23:59:59')
      this.$set(this.form.expenseApplyTrips[index], 'startTime', startTime)
      this.$set(this.form.expenseApplyTrips[index], 'endTime', endTime)
      let day = list && list.length && Number(dayjs(list[1]).diff(dayjs(list[0]), 'day')) + 1
      this.$set(this.form.expenseApplyTrips[index], 'tripDay', day)
      this.$nextTick(() => {
        this.$refs.form.clearValidate([`expenseApplyTrips.${index}.tripDay`])
      })

    },
    downloadFile(obj) {
      this.fileUrl = obj.url
      if (this.fileUrl.indexOf('png') || this.fileUrl.indexOf('jpg')) {
        // this.previewFile = true
        window.open(this.fileUrl);
      } else {
        this.previewFile = true
      }
    },
    handleOutSubmit() {

    },
    handleLsCl() {
      this.lsIsOpen = false
    },
    handleLsCm(list) {
      this.$set(this.form.expenseApplyTrips[this.index], 'tripPartners', list)
      this.lsIsOpen = false
    },
    handleShowFw(list, index) {
      this.selectIds = list
      this.index = index
      this.lsIsOpen = true
    },
    handleInit(list) {
      this.userList = list
    },
    handleTgCl() {
      this.tgIsOpen = false
    },
    handleTgCm(list) {
      let flag = (list.filter(item => this.selectUserIds.includes(item)) || [])
      if (flag.length) {
        const { username } = this.userList.find(item => item.id === flag[0])
        this.$modal.msgError(`同行人${username}已经被添加，请勿重复添加！`);
      } else {
        list.forEach(v => {
          this.form.expenseApplyTrips[this.index].tripPartners.push(v)
        })
        this.tgIsOpen = false
      }
    },
    handleAddFw(index) {
      this.index = index
      this.tgIsOpen = true
      this.selectUserIds = this.form.expenseApplyTrips[index].tripPartners
    },
    handleDelRode(index) {
      this.form.expenseApplyTrips.splice(index, 1)
    },
    handleAddRode() {
      this.form.expenseApplyTrips.push({
        time: null,
        startTime: null,
        endTime: null,
        departureLocation: null,
        destinationLocation: null,
        tripDay: undefined,
        tripType: null,
        tripPartners: [], // 出差同行人
        amount: undefined
      })
    },
    //上传文件的事件
    uploadFile(item) {
      //上传文件的需要formdata类型;所以要转
      let FormDatas = new FormData()
      FormDatas.append('file', item.file);
      FormDatas.append('path', item.file.name);
      uploadFileApi(FormDatas).then((res) => {
        this.fileList.push({ name: item.file.name, url: res.data });//成功过后手动将文件添加到展示列表里
        if (this.fileList.length > 0) {//如果上传了附件就把校验规则给干掉
          this.fileflag = false;
        }
        this.$modal.closeLoading()
      })
    },
    //上传了的文件给移除的事件，由于我没有用到默认的展示，所以没有用到
    handleRemove() {
    },
    //这是我自定义的移除事件
    handleClose(i) {
      this.fileList.splice(i, 1);//删除上传的文件
      if (this.fileList.length == 0) {//如果删完了
        this.fileflag = true;//显示url必填的标识
        // this.$set(this.demoObj.url, 0, { required: true, validator: this.validatorUrl, trigger: 'blur' })//然后动态的添加本地方法的校验规则
      }
    },
    handleInitForm(id) {
      this.processInstanceLoading = true
      getExpenseApply(id).then(response => {
        this.form = response.data || {};
        if (this.$route.query.typeStr === 'business') {
          this.form.expenseApplyTrips = this.form.expenseApplyTrips.map((item) => {
            return {
              ...item,
              departureLocation: Number(item.departureLocation),
              destinationLocation: Number(item.destinationLocation),
              amount: item.amount ? item.amount : undefined,
              time: [new Date(dayjs(item.startTime).format('YYYY/MM/DD')), new Date(dayjs(item.endTime).format('YYYY/MM/DD'))]
            }
          })
        }
        this.fileList = this.form.files || []
        this.$nextTick(() => {
          this.form.processInstanceId && this.$refs.FlowDialog.getDetail(this.form.processInstanceId)
        })
        this.isAuthorised = this.form.isAuthorised
      });
    },
    submitForm(type) {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        // 添加/修改的提交
        let newForm = {
          ...this.form,
          billType: this.$route.query.typeStr == 'business' ? 'CLSQ' : 'RCSQ',
          status: type,
          files: this.fileList,
          expenseApplyTrips: (this.form.expenseApplyTrips || []).map(
            item => {
              return {
                ...item,
                departureLocation: Array.isArray(item.departureLocation) ? item.departureLocation[item.departureLocation.length - 1] : item.departureLocation,
                destinationLocation: Array.isArray(item.destinationLocation) ? item.destinationLocation[item.destinationLocation.length - 1] : item.destinationLocation,
                startTime: dayjs(item.startTime).valueOf(),
                endTime: dayjs(item.endTime).valueOf()
              }
            }
          )
        }
        if (this.$route.query.typeStr == 'daily') {
          delete newForm.expenseApplyTrips
        }

        createExpenseApply(newForm).then(response => {
          this.$modal.msgSuccess(`${this.form.id ? '修改成功!' : '新增成功!'}`);
          history.back()
        });
      });
    },
    cancel() {
      this.$emit('onCancel')
    },
  }
}
</script>
<style lang="scss" scoped>
@import '@/assets/styles/form/index.scss';
.my-process-designer {
  background: #fff !important;
}
</style>