<template>
  <view>
    <Navbar :title="title" />
    <div class="content">
      <!-- 工程基本信息 -->
      <div class="projectInfo">
        <div class="projectInfo-top">
          <div class="title-wrapper">
            <span class="line"></span>
            <span class="title">工程基本信息</span>
          </div>
          <div v-if="formData.projectTypeId == 2">
            <u-button text="新建" type="primary" size="mini" @click="addSupervision"></u-button>
          </div>
        </div>

        <!-- 表单 -->
        <u-form
          labelPosition="left"
          :model="formData"
          :rules="rules"
          ref="uForm"
          labelWidth="120"
          :labelStyle="{ fontWeight: 400, fontSize: '12px', color: 'rgba(15, 39, 75, 0.6)' }"
        >
          <!-- 工程名称 -->
          <u-form-item label="工程名称" prop="projectName" borderBottom required>
            <u-input
              v-model="formData.projectName"
              border="none"
              inputAlign="right"
              fontSize="12"
              color="#0F274B"
              maxlength="32"
              @blur="handleCheckProName"
            ></u-input>
          </u-form-item>

          <!-- 工程负责人 -->
          <u-form-item label="工程负责人" prop="name" borderBottom required>
            <u-picker
              :show="showPerson"
              :columns="nameList"
              @cancel="showPerson = false"
              @confirm="confirmPerson"
              keyName="label"
            ></u-picker>
            <div class="form-select" @click="handleShowPerson">
              <span class="form-name">{{ formData.name }}</span>
              <span class="please-select">请选择</span>
              <u-icon slot="right" name="arrow-right"></u-icon>
            </div>
          </u-form-item>

          <!-- 联系方式 -->
          <u-form-item label="联系方式" prop="phone" borderBottom required>
            <u-input
              v-model="formData.phone"
              border="none"
              inputAlign="right"
              fontSize="12"
              color="#0F274B"
              disabled
              disabledColor="#fff"
            ></u-input>
          </u-form-item>

          <!-- 计划开工时间 -->
          <u-form-item label="计划开工时间" prop="startTime" borderBottom required>
            <u-datetime-picker
              :show="showStartDate"
              v-model="formData.nowTime"
              mode="date"
              @cancel="showStartDate = false"
              @confirm="confirmStartDate"
            ></u-datetime-picker>
            <div class="form-select" @click="handleShowStartDate">
              <span class="form-name">{{ formData.startTime }}</span>
              <u-icon name="calendar"></u-icon>
              <u-icon slot="right" name="arrow-right"></u-icon>
            </div>
          </u-form-item>

          <!-- 计划竣工时间 -->
          <u-form-item label="计划竣工时间" prop="endTime" borderBottom required>
            <u-datetime-picker
              :show="showEndDate"
              v-model="formData.nowTime"
              mode="date"
              @cancel="showEndDate = false"
              @confirm="confirmEndDate"
            ></u-datetime-picker>
            <div class="form-select" @click="handleShowEndDate">
              <span class="form-name">{{ formData.endTime }}</span>
              <u-icon name="calendar"></u-icon>
              <u-icon slot="right" name="arrow-right"></u-icon>
            </div>
          </u-form-item>

          <!-- 工程类型 -->
          <u-form-item label="工程类型" prop="projectType" borderBottom required>
            <u-picker
              :show="showProjectType"
              :columns="projectTypeList"
              @cancel="showProjectType = false"
              @confirm="confirmProjectType"
              keyName="label"
            ></u-picker>
            <div class="form-select" @click="handleShowProjectType">
              <span class="form-name">{{ formData.projectType }}</span>
              <span class="please-select">请选择</span>
              <u-icon slot="right" name="arrow-right"></u-icon>
            </div>
          </u-form-item>

          <!-- 选择监理单位 -->
          <u-form-item label="选择监理单位" prop="supervision" borderBottom required v-if="formData.projectTypeId == 2">
            <u-picker
              :show="showSupervision"
              :columns="supervisionList"
              @cancel="showSupervision = false"
              @confirm="confirmSupervision"
              keyName="label"
            ></u-picker>
            <div class="form-select" @click="handleShowSupervision">
              <span class="form-name">{{ formData.supervision }}</span>
              <span class="please-select">请选择</span>
              <u-icon slot="right" name="arrow-right"></u-icon>
            </div>
          </u-form-item>
        </u-form>
      </div>

      <!-- 工程地址配置 -->
      <div class="projectInfo">
        <div class="projectInfo-top">
          <div class="title-wrapper">
            <span class="line"></span>
            <span class="title">工程地址配置</span>
          </div>
          <div><u-button text="新建" type="primary" size="mini" @click="addNewProjectAddress"></u-button></div>
        </div>

        <!-- 表单 -->
        <u-form
          labelPosition="left"
          :model="formDataAddress"
          ref="addressForm"
          labelWidth="120"
          :labelStyle="{ fontWeight: 400, fontSize: '12px', color: 'rgba(15, 39, 75, 0.6)' }"
        >
          <div v-for="(item, index) in formDataAddress.proAddress">
            <u-form-item>
              <template slot="right">
                <span class="right-content">
                  <u--image
                    v-show="index > 0"
                    src="/static/images/imgs/delete.png"
                    width="16px"
                    height="16px"
                    style="margin-left: 14px"
                    @click="rmProjectAddress(index)"
                  ></u--image>
                </span>
              </template>
            </u-form-item>
            <!-- 工程地址 -->
            <u-form-item :label="`工程地址${index + 1}`" borderBottom required prop="label">
              <u-picker
                :show="showProjectAddress"
                :columns="projectAddressList"
                keyName="label"
                @cancel="showProjectAddress = false"
                @confirm="confirmAddress"
              ></u-picker>
              <div class="form-select" @click="handleShowAddress(index)">
                <span class="form-name">{{ item.label }}</span>
                <span class="please-select">请选择</span>
                <u-icon slot="right" name="arrow-right"></u-icon>
              </div>
            </u-form-item>

            <!-- 经度 -->
            <u-form-item label="经度" borderBottom required style="text-align: right" prop="lon">
              <template slot="right">
                <span class="right-content">{{ item.lon }}</span>
              </template>
            </u-form-item>

            <!-- 纬度 -->
            <u-form-item label="纬度" borderBottom required prop="lat">
              <template slot="right">
                <span class="right-content">{{ item.lat }}</span>
              </template>
            </u-form-item>
          </div>
          <u-form-item>
            <template slot="right">
              <span class="right-content">
                <u--image
                  src="/static/images/imgs/add.png"
                  width="16px"
                  height="16px"
                  @click="addProjectAddress"
                ></u--image>
              </span>
            </template>
          </u-form-item>
        </u-form>
      </div>

      <!-- 承包商配置 -->
      <div class="projectInfo">
        <div class="projectInfo-top">
          <div class="title-wrapper">
            <span class="line"></span>
            <span class="title">承包商配置</span>
          </div>
          <div><u-button text="新建" type="primary" size="mini" @click="addNewContractor"></u-button></div>
        </div>

        <!-- 表单 -->
        <u-form
          labelPosition="left"
          :model="formDataContractor"
          ref="addressForm"
          labelWidth="120"
          :labelStyle="{ fontWeight: 400, fontSize: '12px', color: 'rgba(15, 39, 75, 0.6)' }"
        >
          <div v-for="(item, index) in formDataContractor.projectContractors">
            <u-form-item>
              <template slot="right">
                <span class="right-content">
                  <u--image
                    v-show="index > 0"
                    src="/static/images/imgs/delete.png"
                    width="16px"
                    height="16px"
                    style="margin-left: 14px"
                    @click="rmContractor(index)"
                  ></u--image>
                </span>
              </template>
            </u-form-item>
            <!-- 承包商 -->
            <u-form-item :label="`承包商${index + 1}`" borderBottom required prop="label">
              <u-picker
                :show="showContractor"
                :columns="contractorList"
                keyName="label"
                @cancel="showContractor = false"
                @confirm="confirmContractor"
              ></u-picker>
              <div class="form-select" @click="handleShowContractor(index)">
                <span class="form-name">{{ item.label }}</span>
                <span class="please-select">请选择</span>
                <u-icon slot="right" name="arrow-right"></u-icon>
              </div>
            </u-form-item>

            <!-- 承包商入场材料 -->
            <u-form-item :label="`承包商入场材料${index + 1}`" borderBottom required labelPosition="top">
              <!-- 多选框 -->
              <u-checkbox-group
                v-model="item.checkList"
                placement="row"
                @change="checkboxChange"
                style="margin-top: 10px"
                size="13"
              >
                <u-checkbox
                  :customStyle="{ margin: '8px', fontSize: '13px' }"
                  v-for="(item, index) in contractorMaterialList"
                  :key="index"
                  :label="item.label"
                  :name="item.value"
                ></u-checkbox>
              </u-checkbox-group>
            </u-form-item>
          </div>
          <u-form-item>
            <template slot="right">
              <span class="right-content">
                <u--image
                  src="/static/images/imgs/add.png"
                  width="16px"
                  height="16px"
                  @click="addContractor"
                ></u--image>
              </span>
            </template>
          </u-form-item>
        </u-form>
      </div>
      <!-- 提交 -->
      <div class="form-btn-wrapper">
        <u-button class="formBtn" type="primary" shape="circle" @click="submit">提交</u-button>
        <u-button class="formBtn" shape="circle" @click="goBack">取消</u-button>
      </div>
    </div>
  </view>
</template>

<script>
import moment from 'moment'
import {
  getProLeaderOption,
  getDictTableOption,
  selectSupervisionUnit,
  selectProAddress,
  selectConsUnit,
  selectConsMaterial,
  addProInfo,
  proDetails,
  editPro,
  checkIsExistProName
} from '@/api/project'

export default {
  data() {
    return {
      isLoading: false,
      showPerson: false, // 是否显示工程负责人-picker
      showStartDate: false, // 是否显示开始时间-picker
      showEndDate: false, // 是否显示结束时间-picker
      showProjectType: false, // 是否显示工程类型-picker
      showSupervision: false, // 是否显示监理单位-picker
      showContractor: false, // 是否显示承包商-picker
      showContractorMaterial: false, // 是否显示承包商入场材料-picker,
      proId: '', // 工程id
      title: '新建工程', // 页面标题
      // 基本信息
      formData: {
        projectName: '',
        name: '',
        nameId: '',
        phone: '',
        nowTime: moment(new Date()).format('YYYY-MM-DD'),
        startTime: '',
        endTime: '',
        projectType: '',
        projectTypeId: '',
        supervision: '',
        supervisionId: ''
      },
      // 工程负责人-Picker
      nameList: [],
      // 工程类型-Picker
      projectTypeList: [],
      // 监理单位-Picker
      supervisionList: [],
      rules: {
        projectName: {
          type: 'string',
          required: true,
          message: '请填写工程名称',
          trigger: ['blur', 'change']
        },
        name: {
          type: 'string',
          required: true,
          message: '请选择工程负责人',
          trigger: ['blur', 'change']
        },
        phone: [
          {
            required: true,
            message: '请填写联系方式',
            trigger: ['blur', 'change']
          }
        ],
        startTime: {
          type: 'string',
          required: true,
          message: '请选择计划开工时间',
          trigger: ['blur', 'change']
        },
        endTime: {
          type: 'string',
          required: true,
          message: '请选择计划竣工时间',
          trigger: ['blur', 'change']
        },
        projectType: {
          type: 'string',
          required: true,
          message: '请选择工程类型',
          trigger: ['blur', 'change']
        },
        supervision: {
          type: 'string',
          required: true,
          message: '请选择监理单位',
          trigger: ['blur', 'change']
        }
      },
      showProjectAddress: false, // 是否显示工程地址-picker
      // 工程地址
      formDataAddress: {
        index: 0,
        proAddress: [
          {
            value: '',
            label: '',
            lon: '',
            lat: '',
            key: Date.now()
          }
        ]
      },
      // 工程地址-picker
      projectAddressList: [],
      // 承包商
      formDataContractor: {
        index: 0,
        projectContractors: [
          {
            value: '',
            label: '',
            // 入场材料
            checkList: [],
            key: Date.now()
          }
        ]
      },
      // 承包商-picker
      contractorList: [],
      // 承包商入场材料-picker
      contractorMaterialList: []
      // 背景图
      // bgColor: url('/static//images/imgs/nav.png')
      // background: {
      //   backgroundImage: 'url(/static//images/imgs/nav.png)',
      //   backgroundSize: '100% 100%',
      //   backgroundRepeat: 'no-repeat'
      // }
    }
  },
  onLoad(opt) {
    if (!opt.params) return
    opt = JSON.parse(opt.params)
    this.proId = opt.proId
    if (opt.isEdit) {
      this.title = '编辑工程'
    }
    this.getInfo()
    console.log('🚀 opt ->', opt)
  },
  mounted() {
    this.handleShowContractorMaterial()
  },
  methods: {
    // 获取工程详情
    getInfo() {
      console.log('🚀 this.proId ->', this.proId)
      proDetails({ proId: this.proId }).then(res => {
        console.log('🚀 ~ proDetails ~ res:', res)
        this.formData.projectName = res.projectInfo[0].proName
        this.formData.name = res.projectInfo[0].proLeader
        this.formData.nameId = res.projectInfo[0].proLeaderId
        this.formData.phone = res.projectInfo[0].proLeaderPhone
        this.formData.startTime = res.projectInfo[0].startDate
        this.formData.endTime = res.projectInfo[0].endDate
        this.formData.projectType = res.projectInfo[0].proTypeName
        this.formData.projectTypeId = res.projectInfo[0].proType
        this.formData.supervision = res.projectInfo[0].supervisorUnit
        this.formData.supervisionId = res.projectInfo[0].supervisorUnitId
        this.formDataAddress.proAddress = res.projectInfo[0].proAddress
        this.formDataContractor.projectContractors = res.projectInfo[0].consArr
      })
    },
    // 检查工程名称唯一性
    handleCheckProName() {
      const params = {
        proId: this.proId || '',
        proName: this.formData.projectName
      }
      return checkIsExistProName(params)
        .then(res => {
          console.log('checkIsExistProName', res)
          return true
        })
        .catch(err => {
          console.log('checkIsExistProName-err', err)
          return false
        })
    },
    goBack() {
      // 返回pages/index
      // this.$router.push('/pages/index')
      uni.navigateBack()
    },
    // 添加监理
    addSupervision() {
      // this.$router.push('/pages/newProject/newSupervision')
      uni.navigateTo({
        url: '/pages/newProject/newSupervision'
      })
    },
    // 添加工程地址
    addNewProjectAddress() {
      uni.navigateTo({
        url: '/pages/newProject/newProjectAddress'
      })
    },
    // 添加承包商
    addNewContractor() {
      uni.navigateTo({
        url: '/pages/newProject/newContractor'
      })
    },
    // 显示工程负责人
    handleShowPerson() {
      console.log('handleShowPerson', this.showPerson)
      getProLeaderOption().then(res => {
        console.log('getProLeaderOption', res)
        this.nameList = [res.data]
        this.showPerson = !this.showPerson
      })
    },
    // 选择工程负责人
    confirmPerson(val) {
      this.$refs.uForm.validateField('name')
      console.log('confirmPerson', val.value[0])
      this.formData.name = val.value[0].label
      this.formData.nameId = val.value[0].value
      this.formData.phone = val.value[0].phone
      this.showPerson = false
    },
    // 显示开始时间
    handleShowStartDate() {
      this.showStartDate = !this.showStartDate
    },
    // 选择开始时间
    confirmStartDate(val) {
      this.$refs.uForm.validateField('startTime')
      console.log('confirmStartDate', val.value)
      this.formData.startTime = moment(val.value).format('YYYY-MM-DD')
      this.showStartDate = false
      console.log('confirmStartDate', this.formData.startTime)
    },
    // 显示结束时间
    handleShowEndDate() {
      this.showEndDate = !this.showEndDate
    },
    // 选择结束时间
    confirmEndDate(val) {
      this.$refs.uForm.validateField('endTime')
      console.log('confirmEndDate', val.value)
      this.formData.endTime = moment(val.value).format('YYYY-MM-DD')
      this.showEndDate = false
      console.log('confirmEndDate', this.formData.endTime)
    },
    // 显示工程类型
    handleShowProjectType() {
      const params = {
        dictType: 'sys_pro_type',
        dictValue: ''
      }
      getDictTableOption(params).then(res => {
        console.log('getDictTableOption', res)
        this.projectTypeList = [res.data]
        this.showProjectType = !this.showProjectType
      })
    },
    // 选择工程类型
    confirmProjectType(val) {
      this.$refs.uForm.validateField('projectType')
      console.log('confirmProjectType', val.value[0])
      this.formData.projectType = val.value[0].label
      this.formData.projectTypeId = val.value[0].value
      if (this.formData.projectTypeId == 1) {
        this.formData.supervision = ''
        this.formData.supervisionId = ''
      }
      this.showProjectType = false
    },
    // 显示监理单位
    handleShowSupervision() {
      selectSupervisionUnit().then(res => {
        console.log('selectSupervisionUnit', res)
        this.supervisionList = [res.data]
        this.showSupervision = !this.showSupervision
      })
    },
    // 选择监理单位
    confirmSupervision(val) {
      this.$refs.uForm.validateField('supervision')
      console.log('confirmSupervision', val.value[0])
      this.formData.supervision = val.value[0].label
      this.formData.supervisionId = val.value[0].value
      this.showSupervision = false
    },
    // 显示工程地址
    handleShowAddress(index) {
      selectProAddress().then(res => {
        console.log('selectProAddress', res)
        this.projectAddressList = [res.data]
        this.showProjectAddress = true
        this.formDataAddress.index = index
      })
    },
    // 选择工程地址
    confirmAddress(val) {
      console.log('🚀 ~ confirmAddress ~ val:', val)
      const index = this.formDataAddress.index
      this.formDataAddress.proAddress[index].value = val.value[0].value
      this.formDataAddress.proAddress[index].label = val.value[0].label
      this.formDataAddress.proAddress[index].lon = val.value[0].lon
      this.formDataAddress.proAddress[index].lat = val.value[0].lat
      this.showProjectAddress = false
    },
    // 添加工程地址
    addProjectAddress() {
      this.formDataAddress.proAddress.push({
        value: '',
        label: '',
        lon: '',
        lat: '',
        key: Date.now()
      })
    },
    // 删除工程地址
    rmProjectAddress(index) {
      this.formDataAddress.proAddress.splice(index, 1)
    },
    // 显示承包商
    handleShowContractor(index) {
      selectConsUnit().then(res => {
        console.log('selectConsUnit', res)
        this.contractorList = [res.data]
        this.showContractor = true
        this.formDataContractor.index = index
      })
    },
    // 选择承包商
    confirmContractor(val) {
      const index = this.formDataContractor.index
      this.formDataContractor.projectContractors[index].label = val.value[0].label
      this.formDataContractor.projectContractors[index].value = val.value[0].value
      this.showContractor = false
    },
    // 显示承包商入场材料
    handleShowContractorMaterial(index) {
      selectConsMaterial().then(res => {
        console.log('selectConsMaterial', res)
        this.contractorMaterialList = res.data
        this.showContractorMaterial = true
        this.formDataContractor.index = index
      })
    },
    // 选择承包商入场材料
    checkboxChange(val) {
      console.log('checkboxChange', val)
      console.log('🚀 ~ checkboxChange ~ .checkList:', this.formDataContractor)
    },
    // confirmContractorMaterial(val) {
    //   const index = this.formDataContractor.index
    //   this.formDataContractor.projectContractors[index].checkList = val.value[0].label
    //   this.formDataContractor.projectContractors[index].contractorMaterialId = val.value[0].value
    //   this.showContractorMaterial = false
    // },
    // 添加承包商
    addContractor() {
      this.formDataContractor.projectContractors.push({
        label: '',
        value: '',
        checkList: [],
        key: Date.now()
      })
    },
    // 删除承包商
    rmContractor(index) {
      this.formDataContractor.projectContractors.splice(index, 1)
    },

    // 提交
    async submit() {
      const isCheck = await this.handleCheckProName()
      console.log('🚀 ~ submit ~ 工程是否唯一:', isCheck)
      if (!isCheck) return
      console.log('submit', this.formData)
      console.log('submit-addr', this.formDataAddress)
      console.log('submit-label', this.formDataContractor)
      // 校验
      this.$refs.uForm.validate().then(valid => {
        if (this.formData.startTime > this.formData.endTime) {
          // 提示
          this.$u.toast('开工时间不能晚于竣工时间')
          return
        }
        // 定义一个变量, 用于判断是否校验通过
        let flag = true
        // 校验工程地址-未选择提示请选择, 地址相同提示不能重复
        this.formDataAddress.proAddress.forEach(item => {
          console.log('🚀 ~ submit ~ item:', item)
          if (!item.label) {
            this.$u.toast('请选择工程地址')
            flag = false
          } else {
            const addressList = this.formDataAddress.proAddress.map(item => item.label)
            const addressSet = new Set(addressList)
            if (addressList.length !== addressSet.size) {
              this.$u.toast('工程地址不能重复')
              flag = false
            }
          }
        })
        // 校验承包商-未选择提示请选择, 承包商相同提示不能重复
        this.formDataContractor.projectContractors.forEach(item => {
          if (!item.label) {
            this.$u.toast('请选择承包商')
            flag = false
          } else if (item.checkList.length === 0) {
            this.$u.toast('请选择承包商入场材料')
            flag = false
          } else {
            const contractorList = this.formDataContractor.projectContractors.map(item => item.label)
            const contractorSet = new Set(contractorList)
            if (contractorList.length !== contractorSet.size) {
              this.$u.toast('承包商不能重复')
              flag = false
            }
          }
        })
        if (!flag) return

        const params = {
          proId: this.proId,
          proName: this.formData.projectName,
          proLeader: this.formData.name,
          proLeaderId: this.formData.nameId,
          proLeaderPhone: this.formData.phone,
          proType: this.formData.projectTypeId,
          startDate: this.formData.startTime,
          endDate: this.formData.endTime,
          supervisorUnit: this.formData.supervision || undefined,
          supervisorUnitId: this.formData.supervisionId || undefined,
          proAddress: this.formDataAddress.proAddress,
          consArr: this.formDataContractor.projectContractors
        }
        console.log('🚀 ~ submit ~ params:', params)
        // 提交
        if (this.isLoading) return
        this.isLoading = true
        uni.showLoading({
          title: '加载中'
        })

        if (this.proId) {
          editPro(params)
            .then(res => {
              console.log('editPro', res)
              if (res.code === 200) {
                uni.showToast({
                  title: '操作成功',
                  icon: 'success'
                })
                setTimeout(() => {
                  uni.navigateBack()
                  uni.hideLoading()
                  this.isLoading = false
                }, 1000)
              }
            })
            .catch(err => {
              console.log('🚀 ~ submit ~ err:', err)
              this.isLoading = false
              uni.hideLoading()
            })
        } else {
          addProInfo(params)
            .then(res => {
              console.log('addProInfo', res)
              if (res.code === 200) {
                uni.showToast({
                  title: '操作成功',
                  icon: 'success'
                })
                setTimeout(() => {
                  uni.navigateBack()
                  uni.hideLoading()
                  this.isLoading = false
                }, 1000)
              }
            })
            .catch(err => {
              console.log('🚀 ~ addProInfo ~ err:', err)
              this.isLoading = false
              uni.hideLoading()
            })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.content {
  width: 100%;
  height: 100%;
  background-color: #fff;

  .projectInfo {
    margin: 0 25px 20px;
    .projectInfo-top {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .title-wrapper {
        display: flex;
        justify-content: start;
        align-items: center;
        padding: 10px 0;
        .line {
          margin-right: 8px;
          width: 3px;
          height: 16px;
          background: #3783ff;
          border-radius: 0px 0px 0px 0px;
        }
        .title {
          font-weight: 500;
          font-size: 14px;
          color: #0f274b;
        }
      }
    }
  }

  .form-select {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .form-name {
      width: calc(100% - 60px);
      margin-right: 5px;
      font-weight: 500;
      font-size: 12px;
      color: #0f274b;
      text-align: right;
    }
    .please-select {
      font-weight: 400;
      font-size: 12px;
      color: rgba(15, 39, 75, 0.4);
    }
  }

  .right-content {
    display: flex;
    font-weight: 500;
    font-size: 12px;
    color: #0f274b;
  }

  .form-btn-wrapper {
    margin-top: 40px;
    height: 160px;
    .formBtn {
      width: 90%;
      margin-bottom: 20px;
    }
  }
}
</style>
