<template>
    <!-- 协议管理 新增、编辑 表单组件 -->
    <div>
        <el-form
            label-width="100px"
            size="medium"
            ref="protocolParamsRef"
            :model="protocolParams"
            :rules="protocolParamsRules"
        >
            <el-row type="flex" justify="space-between" :gutter="24">
                <el-col :span="12">
                    <el-form-item label="租赁单位" prop="customer">
                      <treeselect
                        v-model="protocolParams.customer"
                        :options="unitSelRange"
                        noChildrenText="没有数据了"
                        noOptionsText="没有数据"
                        noResultsText="没有搜索结果"
                        placeholder="请选择所属上级"
                      />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="授权人" prop="authorizingPerson">
                        <el-input v-model="protocolParams.authorizingPerson" />
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="24">
                <el-col :span="12">
                    <el-form-item label="租赁工程" prop="project">
                      <treeselect
                        v-model="protocolParams.project"
                        :options="projSelRange"
                        noChildrenText="没有数据了"
                        noOptionsText="没有数据"
                        noResultsText="没有搜索结果"
                        placeholder="请选择所属上级"
                        @before-select="handleBeforeSelect"
                      />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="联系电话" prop="authorizingPhone">
                      <el-input v-model="protocolParams.authorizingPhone" :maxlength="11" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="24">
                <el-col :span="12">
                    <el-form-item label="合同编号" prop="contractNumber">
                      <el-input v-model="protocolParams.contractNumber" />
                    </el-form-item>
                </el-col>
<!--                <el-col :span="12">
                    <el-form-item label="租赁期限" prop="pro_nature">
                        <el-select
                            v-model="protocolParams.pro_nature"
                        ></el-select>
                    </el-form-item>
                </el-col>-->
                <el-col :span="12">
                  <el-form-item label="开始日期" prop="startTime">
<!--                    <el-input v-model="protocolParams.startTime" />-->
                    <el-date-picker
                      style="width: 100%"
                      v-model="protocolParams.startTime"
                      type="date"
                      value-format="yyyy-MM-dd"
                      placeholder="选择日期">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="24">
                <el-col :span="12">
                    <el-form-item label="备注" prop="remark">
                        <el-input v-model="protocolParams.remark" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="合同附件" prop="url">
                    <el-upload
                      :http-request="(obj) => uploadData(obj)"
                      action="#"
                      :file-list="fileList"
                      :on-exceed="fileExceed"
                      :on-remove="handleRemove"
                      list-type="picture-card"
                      accept=".png, .jpg, .jpeg"
                      :limit="1"
                    >
<!--                      <img
                        v-if="protocolParams.url"
                        :src="protocolParams.url"
                        style="width: 140px; height: 140px"
                        class="avatar"
                      />-->
                      <i class="el-icon-plus"></i>
                    </el-upload>
                  </el-form-item>
                </el-col>
            </el-row>
<!--            <el-row :gutter="24">
                <el-col :span="12"> </el-col>
            </el-row>-->

            <el-form-item>
                <el-button type="success" @click="onSubmit">确认</el-button>
                <el-button
                    @click="
                        () => {
                            this.$emit('closeDialog')
                        }
                    "
                    >取消</el-button
                >
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import {
  addProtocolApi,
  editProtocolApi,
  queryleaseProjApi,
  queryleaseUnitApi
} from '@/api/base/agreement'
import {
  queryProjectSelApi
} from '@/api/base/project'
import {
  fileUpLoad,
  imgUpLoad
} from '@/api/system/upload'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
    name: 'FormProtocol',
    props: {
        editParams: {
            type: Object,
            default: () => null,
        },
    },
    components: { Treeselect },
    created() {
      this.getRanges()
    },
    mounted() {
        if (this.editParams) {
            Object.assign(this.protocolParams, this.editParams)
            this.subSort = 2
        } else {
            this.subSort = 1
        }
    },
    data() {
        return {
            subSort: '', // 提交类型：新增 1 / 修改 2
            protocolParams: {
                customer: undefined, // 租赁单位
                authorizingPerson: undefined, // 授权人
                project: undefined, // 租赁工程
                authorizingPhone: undefined, // 联系电话
                contractNumber: undefined, // 合同编号
                startTime: undefined, // 开始日期
                remark: undefined, // 备注
                url: undefined, // 合同附件
            },
            // 图片集合
            picList: [],
            // 图片名称集合
            picNameList: [],
            //
            fileList: [],
            // 租赁单位下拉框
            unitSelRange: [],
            // 租赁工程下拉框
            projSelRange: [],
            // 校验规则
            protocolParamsRules: {
                customer: [
                    {
                        required: true,
                        message: '请选择租赁单位',
                        trigger: 'blur',
                    },
                ],
                authorizingPerson: [
                    {
                        required: true,
                        message: '请输入授权人',
                        trigger: 'blur',
                    },
                ],
                project: [
                    {
                        required: true,
                        message: '请选择租赁工程',
                        trigger: 'blur',
                    },
                ],
                authorizingPhone: [
                    {
                        required: true,
                        message: '请输入联系电话',
                        trigger: 'blur',
                    },
                ],
            },
        }
    },
    methods: {
        /** 查询各类下拉框  */
        async getRanges() {
          // 往来单位
          let unitRes = await queryleaseUnitApi()
          this.unitSelRange = unitRes.data
          // 租赁工程
          let projRes = await queryleaseProjApi()
          this.projSelRange = projRes.data
        },
        /** 树禁选父级 */
        changeData(data)  { // 存在子集就不让禁止，父级让禁止
          data.map(item => {
            if (!item.children) {
              item.isDisabled = false
            } else if (item.children && item.children.length > 0){
              item.isDisabled = true
            }
            item.children && item.children.length > 0 && this.changeData(item.children);
          })
          return data;
        },
        handleBeforeSelect(node, isSelected) {
          if (node.children && node.children.length) {
            // Prevent parent nodes from being selected
            return !isSelected;
          }
          return true;
        },
        /** 树优化 */
        leadersNormalizer(node) {
          if (node.children && !node.children.length) {
            delete node.children;
          }
          return {
            id: node.id,
            label: node.label,
            children: node.children
          };
        },
        /** 上传图片/文件 */
        uploadData(param) {
          console.log(param)
          imgUpLoad(param).then(res => {
            console.log(res)
            this.picList.push(res.data.url)
            this.picNameList.push(res.data.name.split('_')[0])
          }).catch(err => {})
        },
        /** 文件变化 */
        dataChange(e) {
          console.log(e)
          this.fileList.push(e.raw)
        },
        /** 移除文件 */
        handleRemove(file) {
          console.log(file)
          console.log(this.picNameList)
          this.picList = []
          // this.fileList = this.fileList.filter(item => item.uid !== e.uid)
        },
        /** 文件超出3个 */
        fileExceed() {
          this.$modal.msgError('最多上传1张图片！')
        },
        /** 确认按钮 */
        onSubmit() {
            this.protocolParams.url = this.picList.join()
            console.log(this.protocolParams)
            this.$refs.protocolParamsRef.validate((valid) => {
                if (valid) {
                    console.log('校验通过', this.protocolParams, this.subSort)
                    // 1. 表单校验通过后调后台 Api
                    if(this.subSort === 1) {
                      addProtocolApi(this.protocolParams).then(res => {
                        console.log(res)
                      }).catch(err => {
                        console.log(err)
                      })
                    } else if(this.subSort === 2) {
                      editProtocolApi(this.protocolParams).then(res => {
                        console.log(res)
                      }).catch(err => {
                        console.log(err)
                      })
                    }
                    // 2. 成功之后通知父组件关闭弹框
                    this.$emit('closeDialog', true)
                }
            })
        },
    },
}
</script>

<style scoped>
::v-deep .el-select {
    width: 100%;
}
::v-deep .el-form-item__label{
  font-weight: normal;
}
</style>
