<template>
  <el-form :model="formModel" :rules="createRules" ref="createForm">
    <el-form-item prop="customerId" label="客户" label-width="100px">
      <el-select v-model="formModel.customerId" @change="onCustomerChanged" :disabled="customerIdFixed">
        <el-option
            v-for="item in customerList"
            :key="item.customerId"
            :label="item.customerName"
            :value="item.customerId">
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="选择表单" prop="formId" label-width="100px">
      <el-select v-model="formModel.formId" clearable placeholder="请选择" @change="onFormChanged" :disabled="customerIdFixed">
        <el-option
            v-for="item in formList"
            :key="item.id"
            :label="item.formName"
            :value="item.id">
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item prop="itemGroupId" label="分组" label-width="100px">
      <el-select v-model="formModel.itemGroupId" @change="onGroupChanged">
        <el-option v-for="group in groupList"
                   :key="group.groupId"
                   :label="group.groupLabel"
                   :value="group.groupId">
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item prop="parentItemId" label="父组件" label-width="100px">
      <el-select v-model="formModel.parentItemId">
        <el-option v-for="pi in parentItemsList"
                   :key="pi.id"
                   :label="pi.label"
                   :value="pi.id">
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item prop="tableName" label="数据库表名称" label-width="100px">
      <el-input v-model="formModel.tableName"></el-input>
    </el-form-item>
    <el-form-item prop="columnName" label="数据库列名称" label-width="100px">
      <el-input v-model="formModel.columnName"></el-input>
    </el-form-item>
    <el-form-item prop="label" label="名称" label-width="100px">
      <el-input v-model="formModel.label" style="width: 198px"></el-input>
    </el-form-item>

    <el-form-item prop="required" label="是否必填" label-width="100px">
      <el-checkbox v-model="formModel.required"></el-checkbox>
    </el-form-item>

    <el-form-item prop="itemType" label="组件类型" label-width="100px">
      <el-select v-model="formModel.itemType" @change="onItemTypeChanged">
        <el-option v-for="t in controls" :key="t.type" :value="t.type" :label="t.name"></el-option>
      </el-select>
    </el-form-item>

    <el-form-item prop="itemType" label="选项来源类型" label-width="100px">
      <el-select v-model="formModel.optionSourceType" :disabled="optionSourceTypeDisabled">
        <el-option v-for="t in optionSources" :key="t.type" :value="t.type" :label="t.name"></el-option>
      </el-select>
    </el-form-item>

    <el-form-item prop="itemType" label="选项来源" label-width="100px">
      <el-input v-model="formModel.optionSourceValue" :disabled="optionSourceTypeDisabled"
                placeholder="如果是为直接定义，格式请保持为:  value1:label1,vaalue2:label2。如果是调用api则定义api地址（全为半角符号）"></el-input>
    </el-form-item>

    <el-button @click="onSubmitBtnClick" type="primary">提交</el-button>
    <el-button @click="onCancelBtnClick" type="primary">取消</el-button>
  </el-form>
</template>
<script>

export default {
  data() {
    return {
      // 表单内容
      formModel: {
        customerId: null,
        formId: null,
        itemGroupId: null,
        parentItemId: null,
        label: null,
        tableName: null,
        columnName: null,
        itemType: null,
        required: null,
        optionSourceType: null,
        optionSourceValue: null
      },
      customerIdFixed: false,
      customerList: [],
      formList: [],
      optionSourceTypeDisabled: false,
      createRules: {
        customerId: [
          { required: true, message: '客户为必填项' }
        ],
        formId: [
          { required: true, message: '表单为必填项' }
        ],
        itemGroupId: [
          {required: true, message: '分组为必填项'}
        ],
        label: [
          {required: true, message: '名称为必填项'}
        ],
        itemType: [
          {required: true, message: '组件类型为必填项'}
        ],
        optionSourceType: [
          {required: true, message: '选项来源类型为必填项'}
        ]
        , optionSourceValue: [
          {required: true, message: '选项来源为必填项'}
        ],
      },

      // 分组列表
      groupList: [],

      parentItemsList: [],
      // 组件类型
      controls: [
        {
          type: 'input',
          name: '文本输入框',
        }, {
          type: 'inputNum',
          name: '数字输入框',
        }, {
          type: 'textarea',
          name: '多行文本域',
        }, {
          type: 'select',
          name: '下拉框',
        }, {
          type: 'cascader',
          name: '级联选择器',
        }, {
          type: 'radio',
          name: '单选框',
        }, {
          type: 'checkbox',
          name: '复选框',
        }, {
          type: 'datepicker',
          name: '日期选择器',
        }, {
          type: 'divider',
          name: '分割线',
        }
      ],
      optionSources: [
        {
          type: 'local',
          name: '直接定义',
        }, {
          type: 'remote',
          name: 'api获取',
        }
      ]
    }


  },

  activated() {

    // this.loadCustomerList()

    this.initData({})

  },

  methods: {
    initData({formId: formId, customerId: customerId}) {
      this.formModel.formId = formId;
      this.formModel.customerId = customerId;

      if (formId && customerId) {
        this.customerIdFixed = true;
      } else {
        this.customerIdFixed = false;
      }

      this.loadCustomerList()
      this.loadFormList()
      this.loadGroups();

      // console.log('执行了initData')
    },

    // 加载分组列表
    loadGroups() {
      this.$http.get(`/oper/customize/icform/config/listGroups?formId=${this.formModel.formId}&customerId=${this.formModel.customerId}`)
          .then((resp) => {
            let {data: result} = resp;
            if (result.code !== 0) {
              this.$message({
                type: 'error',
                message: result.msg
              })
              return;
            }

            this.groupList = result.data;
          })
    },

    /**
     * 加载客户列表
     */
    loadCustomerList() {
      this.$http.get('/oper/crm/customer/getvalidcustomerlist').then(({data: res}) => {
        if (res.code === 0) {
          this.customerList = res.data;
          this.customerList.unshift({"customerId": "default", "customerName": "模板"})
        } else {
          this.$message.error(res.msg)
        }
        console.log('客户加载完成')
      })
    },

    /**
     * 加载表单列表
     */
    loadFormList() {
      this.$http.get(`/oper/customize/icform/config/listForms?customerId=${this.formModel.customerId}&formName=&pageNo=1&pageSize=100`)
          .then(({data: httpdata, status: httpStatus}) => {
            if (httpdata.code === 0) {
              this.formList = httpdata.data.list;
            } else {
              this.$message({
                type: 'error',
                nessage: res.msg
              })
            }

            console.log('客户加载完成')
          })
    },

    /**
     * 分组选中
     */
    onGroupChanged() {
      this.$http.get(`/oper/customize/icform/config/listItems?customerId=${this.formModel.customerId}&formId=${this.formModel.formId}&itemGroupId=${this.formModel.itemGroupId}`)
          .then((resp) => {
            let result = resp.data
            if (result.code !== 0) {
              this.$message({
                message: result.msg,
                type: 'error'
              });
              return;
            }

            this.parentItemsList = result.data;
          })
    },

    /**
     * 组件类型选项变更
     */
    onItemTypeChanged(newValue) {
      if (['select', 'cascader', 'radio', 'checkbox'].indexOf(newValue) >= 0) {
        // 如果是这些，则需要定义选项来源
        this.optionSourceTypeDisabled = false;
        this.optionSourceType = "local";
      } else {
        this.optionSourceTypeDisabled = true;
      }
    },

    /**
     * 提交
     */
    onSubmitBtnClick() {
      this.$refs['createForm'].validate(rst => {
        if (!rst) {
          return
        }

        this.$http.post(`/oper/customize/icform/config/createItem`, this.formModel).then(({status:httpStatus, data: httpData}) => {
          if (httpData.code === 0) {
            this.$message({
              type: 'success',
              message:"新增成功"
            });

            this.resetForm()
            this.$emit("onClose") // 关闭窗口
          } else {
            this.$message({
              type: 'error',
              message: httpData.msg
            });
          }
        })
      })

    },

    /**
     * 取消
     */
    onCancelBtnClick() {
      this.resetForm()
      this.$emit("onClose")
    },

    resetForm() {
      this.$refs['createForm'].resetFields();
    },

    /**
     * 客户选中事件
     */
    onCustomerChanged() {
      this.loadFormList()
    },

    onFormChanged() {
      this.loadGroups();
    }
  }


}

</script>
<style lang="scss">
.test {
  width: 100px;
}
</style>
