<!-- 添加/编辑 -->
<template>
  <el-dialog :title="title" :visible.sync="isShow" :close-on-click-modal="false" class="drawer-box" width="700px" @close="handleCancel" append-to-body>
    <el-form ref="form" :model="form" :rules="rules" label-width="150px" label-position="top">
      <el-row>
        <el-col :span="12">
          <el-form-item label="客户名称" prop="code">
            <el-input size="small" v-model="form.code" @focus="handleCustomShow" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="认款部门" prop="code">
            <el-select v-model="form.code" class="wd100" size="small">
              <el-option :value="1" label="已付款"></el-option>
              <el-option :value="2" label="未付款"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="合同名称" prop="appletId">
            <el-date-picker v-model="form.date" class="wd100" type="daterange" size="small" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目名称" prop="name">
            <el-input size="small" v-model="form.name" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="认款人" prop="name">
            <el-input-number size="small" :controls="false" class="wd100 align-left" v-model="form.total" placeholder="请输入"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="认款部门" prop="code">
            <el-select v-model="form.code" class="wd100" size="small">
              <el-option :value="1" label="已付款"></el-option>
              <el-option :value="2" label="未付款"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注信息" prop="name">
            <el-input size="small" type="textarea" :rows="2" v-model="form.total" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button :loading="btnLoading" @click="handleCancel" size="small">取消</el-button>
      <el-button type="primary" :loading="btnLoading" :disabled="disabled" size="small" @click="handleSave">确定</el-button>
    </div>
    <CustomListDialog :isOpen="payShow" :id="selectId" @onCancel="handlePayCancel" @onConfirm="handlePayConfirm" />
  </el-dialog>
</template>

<script>
import { signConfirmApi, lookPayPlanApi, editPayPlanApi } from '@/api/subscription/msg'
import VerifyFunc from '@/utils/verity'
export default {
  name: '',
  props: {
    id: [String, Number],
    isOpen: Boolean,
    disabled: Boolean,
  },
  components: {
    CustomListDialog: () => import('./customListDialog.vue')
  },
  watch: {
    fileList: {
      handler(list) {
        if (list && list.length) {
          this.$nextTick(() => {
            this.$set(this.form, 'logo', 1)
            this.$refs.form.clearValidate(['logo'])
          })
        } else {
          this.$set(this.form, 'logo', null)
        }
      },
      deep: true
    },
    isOpen: {
      handler(val) {
        this.isShow = val
        this.title = '认款'
        if (val) {
          this.handleInitForm()
          // this.handleInitList(this.id)
        }
      },
      deep: true,
      immediate: true
    }
  },
  data() {
    return {
      selectId: 3,
      payShow: false,
      btnLoading: false,
      dialogVisible: false,
      dialogImageUrl: null,
      provinceList: [],
      isShow: false,
      title: '添加学校',
      rules: {
        mobile: [
          { required: true, message: '请输入', trigger: 'blur' },
          { validator: VerifyFunc.rePhone, trigger: 'blur' }
        ],
        logo: [
          { required: true, message: '请上传', trigger: 'change' },
        ],
        appletId: [
          { required: true, message: '请选择', trigger: 'change' },
        ],
        date: [
          { required: true, message: '请选择', trigger: 'change' },
        ],
        code: [
          { required: true, message: '请输入', trigger: 'blur' },
        ],
        name: [
          { required: true, message: '请输入', trigger: 'blur' },
        ],
        total: [
          { required: true, message: '请输入', trigger: 'blur' },
        ],
        type: [
          { required: true, message: '请选择', trigger: 'change' },
        ],
        isCooperativeSchool: [
          { required: true, message: '请选择', trigger: 'change' },
        ],
        region: [
          { required: true, message: '请输入', trigger: 'change' },
        ],
        note: [
          { required: true, message: '请输入', trigger: 'blur' },
        ],
        // sortId: [
        //   { required: false, validator: validatePositiveInteger, trigger: 'blur' }
        // ],
      },
      form: {
        mobile: null,
        date: '',
        appletId: '',
        code: '',
        name: '',
        type: null,
        isCooperativeSchool: 0,
        region: '',
        note: '',
        sortId: 99,
        state: true,
        logoId: null,
        total: undefined,
        planList: [],
      },
      nameArr: [],
      fileList: [],
      isDisabled: true,
    }
  },

  methods: {
    handleCustomShow() {
      console.log('展示信息..');
      this.payShow = true
    },
    handlePayCancel() {
      this.payShow = false
    },
    handlePayConfirm(obj) {
      const { id } = obj
      this.selectId = id
      this.payShow = false
    },
    handleBeginScan() {
      if (!(this.fileList && this.fileList.length)) {
        return this.$fm('请上传营业执照！')
      }
    },
    handleDel() {
      delSchoolListApi(this.id).then(() => {
        this.$sm('删除成功!')
        this.$emit('onConfirm')
      })
    },
    // id 不存在 新增 否则编辑
    handleInitForm(id = this.id) {
      // 初始化参数
      if (!id) {
        this.form = {
          mobile: null,
          date: '',
          appletId: '',
          code: '',
          name: '',
          type: null,
          isCooperativeSchool: 0,
          region: '',
          note: '',
          sortId: 99,
          state: true,
          logoId: null,
          planList: []
        }
        this.fileList = []
        this.$nextTick(() => {
          this.$refs.form && this.$refs.form.resetFields()
          this.$refs.form && this.$refs.form.clearValidate()
        })
      } else {
        schoolDetailListApi(id).then(res => {
          this.form = {
            ...(res.data || {}),
            id,
            state: res.data.state ? true : false,
          }
          this.fileList = [{ url: process.env.VUE_APP_BASE_API + (res.data || {}).logoUrl }]
          this.$nextTick(() => {
            this.$refs.form && this.$refs.form.clearValidate()
          })
        })
      }
    },
    // 0 新增 1 编辑
    handleInitList(id) {
      queryEnrollAppListApi().then(res => {
        this.nameArr = res.data || []
        if (this.nameArr.length == 1) {
          if (!id) {
            this.isDisabled = true
            this.form.appletId = this.nameArr[0].id
          } else {
            this.isDisabled = false
          }
        } else {
          this.isDisabled = false
        }
      })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleClose() {
      this.$emit('onClose')
    },

    handleCommonSubmit(type) {
      let formData = new FormData()
      this.fileList.forEach(item => {
        formData.append('files', item.raw)
      })
      this.btnLoading = true
      if (!type) {
        updateFileApi(formData).then((res) => {
          if (res && res.data && res.data.length) {
            const { id } = res.data[0]
            let listQuery = {
              ...this.form,
              logoId: id,
              state: this.form.state ? 1 : 0
            }
            if (!this.id) {
              addSchoolListApi(listQuery).then(() => {
                this.$sm('添加成功!')
                this.$emit('onConfirm')
                this.btnLoading = false
              }).catch(() => {
                this.btnLoading = false
              })
            } else {
              editSchoolListApi(listQuery).then(() => {
                this.$sm('编辑成功!')
                this.$emit('onConfirm')
                this.btnLoading = false
              }).catch(() => {
                this.btnLoading = false
              })
            }
          } else {
            this.btnLoading = false
          }
        }).catch(() => {
          this.btnLoading = false
        })
      } else {
        let listQuery = {
          ...this.form,
          state: this.form.state ? 1 : 0
        }
        editSchoolListApi(listQuery).then(() => {
          this.$sm('编辑成功!')
          this.$emit('onConfirm')
          this.btnLoading = false
        }).catch(() => {
          this.btnLoading = false
        })
      }
    },
    handleSave() {
      this.$nextTick(() => {
        this.$refs.form.validate((bool) => {
          if (bool) {
            if (!this.fileList.length) {
              this.$fm('请上传营业执照!')
              return
            }
            // 编辑
            if (this.id) {
              if (!this.form.logoUrl) {
                this.handleCommonSubmit()
              } else {
                this.handleCommonSubmit(1)
              }
            } else {
              // 新增
              this.handleCommonSubmit()
            }
          } else {
            this.$nextTick(() => {
              this.$scErr()
            })
          }
        })
      })
    },
    handleCancel() {
      this.$emit('onClose')
    },
    handleRemove(file, files) {
      this.fileList = []
      this.form.logoUrl = null
    },
    onUploadChange(file, files) {
      if (['image/png', 'image/jpeg'].includes(file.raw.type)) {
        if (file.size / 1024 > 5000) {
          setTimeout(() => {
            this.$fm('文件超过5Mb，请压缩后上传!')
          }, 10)
          files.splice(files.length - 1, 1)
          return
        }
        this.fileList = []
        this.fileList.push(file)
      } else {
        this.$fm('不支持此文件类型，请重试！')
      }
    },
  }
}

</script>
<style lang='scss' scoped>
@import '@/assets/styles/edit/index.scss';
</style>