<template>
  <view class="container">
    <Navbar :title="title" canBack></Navbar>
    <u-form labelPosition="left" :model="model" :rules="rules" ref="uForm" errorType="toast">
      <view class="usuallyCard padding margin-sm">
        <view class="text-lg padding-tb">
          基本信息
        </view>
        <view class="padding-lr-sm">
          <!-- 日期选择 -->
          <view class="" v-for="(item,index) in basisData" :key="index">
            <u-form-item :required="item.required" :label="item.label" labelWidth="100" borderBottom
              v-if="item.type === 'date'" :prop="item.key">
              <u-input v-model="model[item.key]" inputAlign="right" :placeholder="item.placeholder" border="none"
                :disabledColor="operationStatus==='YD'?'#F5F7FA':'#fff'"></u-input>
              <u-icon slot="right" name="calendar" size="20" @click="handleDateTime(item)"></u-icon>
              <!-- <u-icon slot="right" name="calendar" size="20" @click="handleDateTime(item)"></u-icon> -->
            </u-form-item>
            <!-- 输入类型 -->
            <u-form-item :required="item.required" :label="item.label" labelWidth="100" borderBottom
              v-if="item.type === 'input'" :prop="item.key">
              <u-input v-model="model[item.key]" inputAlign="right" :placeholder="item.placeholder"
                :disabled="operationStatus ==='YD' || item.key === 'billingPersonName'"
                :disabledColor="operationStatus==='YD'?'#F5F7FA':'#fff'" border="none"></u-input>
              <view class="" style="width: 40rpx;height: 40rpx;"></view>
            </u-form-item>
            <!-- 选择类型 -->
            <u-form-item :required="item.required" :label="item.label" labelWidth="100" borderBottom
              v-if="item.type === 'select'" :disabled="operationStatus ==='YD'" :prop="item.key">
              <u-input v-model="model[item.key]" :disabled="operationStatus ==='YD'" inputAlign="right"
                :placeholder="item.placeholder" :disabledColor="operationStatus==='YD'?'#F5F7FA':'#fff'"
                border="none"></u-input>
              <u-icon slot="right" name="arrow-down" size="20" @click="handleSelect(item)"></u-icon>
            </u-form-item>
          </view>
        </view>
      </view>

      <view class="usuallyCard padding margin-sm">
        <view class="text-lg padding-tb">
          拜访信息
        </view>
        <view class="padding-lr-sm">
          <view class="" v-for="(item,index) in visitData" :key="index">
            <!-- 单选 -->
            <u-form-item :required="item.required" :label="item.label" labelWidth="70%" borderBottom
              v-if="item.type === 'radio' && item.show" :prop="item.key">
              <u-radio-group activeColor="#EA5504" placement="row" v-model="model[item.key]" @change="bfChange"
                :disabled="operationStatus ==='YD'">
                <u-radio class="margin-right" name="是">是</u-radio>
                <u-radio name="否">否</u-radio>
              </u-radio-group>
            </u-form-item>
            <!-- 日期 -->
            <u-form-item :required="item.required" :label="item.label" labelWidth="100" borderBottom
              v-if="item.type === 'date' && item.show" :prop="item.key">
              <u-input v-model="model[item.key]" inputAlign="right" :placeholder="item.placeholder" disabled
                :disabled="operationStatus ==='YD'" disabledColor="#fff" border="none"></u-input>
              <u-icon slot="right" name="calendar" size="20" @click="calendarShow = true"></u-icon>
            </u-form-item>
            <!-- 输入 -->
            <u-form-item :required="item.required" :label="item.label" labelWidth="100" borderBottom
              v-if="item.type === 'input' && item.show" :prop="item.key">
              <u-input v-model="model[item.key]" inputAlign="right" :placeholder="item.placeholder" disabledColor="#fff"
                :disabled="operationStatus ==='YD'" border="none"></u-input>
              <view class="" style="width: 40rpx;height: 40rpx;"></view>
            </u-form-item>
            <!-- 选择 -->
            <u-form-item :required="item.required" :label="item.label" labelWidth="100" borderBottom
              v-if="item.type === 'select' && item.show" :prop="item.key">
              <u-input v-model="model[item.key]" inputAlign="right" :placeholder="item.placeholder" disabledColor="#fff"
                :disabled="operationStatus ==='YD'" border="none"></u-input>
              <u-icon slot="right" name="arrow-down" size="20" @click="handleSelect(item)"></u-icon>
            </u-form-item>
            <!-- 文件 -->
            <u-form-item :required="item.required" :label="item.label" labelWidth="75%" borderBottom
              v-if="item.type === 'file' && item.show" :prop="item.key">
              <u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" name="1" multiple :maxCount="1"
                :disabled="operationStatus ==='YD'" width="100rpx" height="100rpx"></u-upload>
            </u-form-item>
          </view>
        </view>
      </view>

      <view class="usuallyCard padding margin-sm">
        <view class="text-lg  padding-tb">
          决策人信息
        </view>
        <view class="padding-lr-sm">
          <view class="" v-for="(item,index) in decisionMakersData" :key="index">
            <!-- 单选 -->
            <u-form-item :required="item.required" :label="item.label" labelWidth="70%" borderBottom
              v-if="item.type === 'radio' && item.show" :prop="item.key">
              <u-radio-group activeColor="#EA5504" placement="row" v-model="model[item.key]" @change="jcrChange"
                :disabled="operationStatus ==='YD'">
                <u-radio class="margin-right" name="是">是</u-radio>
                <u-radio name="否">否</u-radio>
              </u-radio-group>
            </u-form-item>
            <!-- 输入 -->
            <u-form-item :required="item.required" :label="item.label" labelWidth="120" borderBottom
              v-if="item.type === 'input' && item.show" :prop="item.key">
              <u-input v-model="model[item.key]" inputAlign="right" :placeholder="item.placeholder" disabledColor="#fff"
                :disabled="operationStatus ==='YD'" border="none"></u-input>
              <view class="" style="width: 40rpx;height: 40rpx;"></view>
            </u-form-item>
            <!-- 选择 -->
            <u-form-item :required="item.required" :label="item.label" labelWidth="120" borderBottom
              v-if="item.type === 'select' && item.show" :prop="item.key">
              <u-input v-model="model[item.key]" inputAlign="right" :placeholder="item.placeholder" disabledColor="#fff"
                :disabled="operationStatus ==='YD'" border="none"></u-input>
              <u-icon slot="right" name="arrow-down" size="20" @click="handleSelect(item)"></u-icon>
            </u-form-item>
          </view>
        </view>
      </view>

      <view class="usuallyCard padding margin-sm">
        <view class="text-lg  padding-tb">
          收费信息
        </view>
        <view class="padding-lr-sm">
          <view class="" v-for="(item,index) in chargeData" :key="index">
            <!-- 单选 -->
            <u-form-item :required="item.required" :label="item.label" labelWidth="70%" borderBottom
              v-if="item.type === 'radio' && item.show" :prop="item.key">
              <u-radio-group activeColor="#EA5504" placement="row" v-model="model[item.key]" @change="sfChange">
                <u-radio class="margin-right" name="是">是</u-radio>
                <u-radio name="否">否</u-radio>
              </u-radio-group>
            </u-form-item>
            <!-- 输入 -->
            <u-form-item :required="item.required" :label="item.label" labelWidth="120" borderBottom
              v-if="item.type === 'input' && item.show" :prop="item.key">
              <u-input v-model="model[item.key]" inputAlign="right" :placeholder="item.placeholder" disabledColor="#fff"
                border="none"></u-input>
              <view class="" style="width: 40rpx;height: 40rpx;"></view>
            </u-form-item>
            <!-- 选择 -->
            <u-form-item :required="item.required" :label="item.label" labelWidth="120" borderBottom
              v-if="item.type === 'select' && item.show" :prop="item.key">
              <u-input v-model="model[item.key]" inputAlign="right" :placeholder="item.placeholder" disabled
                disabledColor="#fff" border="none"></u-input>
              <u-icon slot="right" name="arrow-down" size="20" @click="handleSFSelect(item)"></u-icon>
            </u-form-item>
          </view>
        </view>
      </view>

      <view class="usuallyCard padding margin-sm">
        <view class="text-lg  padding-tb">
          其他信息
        </view>
        <view class="padding-lr-sm">
          <view class="" v-for="(item,index) in otherData" :key="index">
            <!-- 输入 -->
            <u-form-item :required="item.required" :label="item.label" labelWidth="120" borderBottom
              v-if="item.type === 'input'">
              <u-input v-model="model[item.key]" inputAlign="right" :placeholder="item.placeholder" disabledColor="#fff"
                border="none"></u-input>
              <view class="" style="width: 40rpx;height: 40rpx;"></view>
            </u-form-item>
            <!-- 附件 -->
            <view class="" v-if="item.type === 'attachment'">
              <u-form-item :required="item.required" :label="item.label" labelWidth="120" borderBottom
                v-if="item.type === 'attachment'">
                <!-- <u-input v-model="model[item.key]" inputAlign="right" :placeholder="item.placeholder" disabled
                  disabledColor="#fff" border="none"></u-input> -->
                <view slot="right" class="text-blue" @click="uploadAttachment">上传附件</view>
              </u-form-item>
              <view class="bg-gray">
                <view class="flex justify-between  flex-direction" v-if="attachmentList.length">
                  <view class="padding" v-for="(item,index) in attachmentList" :key="index">
                    {{item.fileName}}
                  </view>
                  <!-- <view class="">
                    查看
                  </view> -->
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </u-form>
    <view class="fixedBtnCss" @click="handleConfirm">
      <u-button shape="circle" color="#CF000D">{{btnText}}</u-button>
    </view>

    <u-picker :show="pickerShow" ref="uPicker" closeOnClickOverlay :columns="columns" @cancel="pickerShow = false"
      @close="pickerShow = false" keyName="label" @confirm="confirm"></u-picker>

    <u-picker :show="gsShow" ref="gsPicker" closeOnClickOverlay :columns="gsColumns" @cancel="gsShow = false"
      @close="gsShow = false" keyName="label" @confirm="gsConfirm" @change="changeHandler"></u-picker>

    <u-datetime-picker :show="datetimeShow" v-model="dataTimeValue" closeOnClickOverlay @confirm="dateConfirm"
      @cancel="datetimeShow = false" @close="datetimeShow = false" mode="date"></u-datetime-picker>
  </view>
</template>

<script>
  import chargeFile from '@/api/chargeFile'
  import config from '@/common/config.js'
  import {
    getMcFileList,
    getCurrentFiscalYear,
    getCompanyCascader,
    getVlgOrCmty,
    getMcVisitUser,
    addMcVisit,
    editMcVisit,
    modification
  } from '@/api/charge.js'
  export default {
    components: {},
    props: {

    },
    data() {
      return {
        title: "创建拜访/收费",
        btnText: '立即发起',
        operationStatus: '',
        model: {
          fiscalYear: "",
          billingPersonName: "",
          jobNature: "",
          entryTime: "",
          company: "",
          vlgOrCmty: "",
          userName: "",
          userPhone: "",
          companyCode: "",
          address: "",
          userDetailedAddress: "",
          isVisited: "",
          isIntent: "",
          houseCondition: "",
          currentCookingEnergy: "",
          currentHeatingEnergy: "",
          familyMembers: "",
          fridgeStatus: "",
          acStatus: "",
          tvStatus: "",
          washerStatus: "",
          waterHeaterStatus: "",
          pvSystemStatus: "",
          visitDetailedAddress: "",
          fieldPhotoFile: "",
          hasDm: "",
          dmAge: "",
          dmIncomeSrc: "",
          dmPhone: "",
          isCharged: "",
          userCode: "",
          userIdCard: "",
          invoiceNo: "",
          chargeAmt: "",
          paymentMeth: "",
          chargeType: "",
          remark: "",
          attachmentFile: "",
        },
        copyModel: {},
        rules: {
          billingPersonName: [{
            required: true,
            message: '请输入收费人员',
            trigger: ['blur', 'change']
          }],
          jobNature: [{
            required: true,
            message: '请选择工作性质',
            trigger: ['blur', 'change']
          }],
          entryTime: [{
            required: true,
            message: '请选择入户时间',
            trigger: ['blur', 'change']
          }],
          company: [{
            required: true,
            message: '请选择项目公司',
            trigger: ['blur', 'change']
          }],
          vlgOrCmty: [{
            required: true,
            message: '请选择村(小区)',
            trigger: ['blur', 'change']
          }],
          userName: [{
            required: true,
            message: '请选择户名',
            trigger: ['blur', 'change']
          }],
          userPhone: [{
            required: true,
            message: '请填写联系电话',
            trigger: ['blur', 'change']
          }],
          address: [{
            required: true,
            message: '请输入省市区街道',
            trigger: ['blur', 'change']
          }],
          userDetailedAddress: [{
            required: true,
            message: '请填写详细地址',
            trigger: ['blur', 'change']
          }],
          isVisited: [{
            required: true,
            message: '请选择是否拜访',
            trigger: ['blur', 'change']
          }],
          isIntent: [{
            required: true,
            message: '请选择是否有意向',
            trigger: ['blur', 'change']
          }],
          houseCondition: [{
            required: true,
            message: '请选择房屋情况',
            trigger: ['blur', 'change']
          }],
          currentCookingEnergy: [{
            required: true,
            message: '请选择做饭能源',
            trigger: ['blur', 'change']
          }],
          hasDm: [{
            required: true,
            message: '请选择是否决策人信息',
            trigger: ['blur', 'change']
          }],
          dmAge: [{
            required: true,
            message: '请输入决策人年龄',
            trigger: ['blur', 'change']
          }],
          dmIncomeSrc: [{
            required: true,
            message: '选择收入来源',
            trigger: ['blur', 'change']
          }],
          dmPhone: [{
            required: true,
            message: '请填写决策人联系电话',
            trigger: ['blur', 'change']
          }],
          isCharged: [{
            required: true,
            message: '请选择是否收费',
            trigger: ['blur', 'change']
          }],
          userCode: [{
            required: true,
            message: '请填写用户编号',
            trigger: ['blur', 'change']
          }],
          userIdCard: [{
            required: true,
            message: '请填写身份证号',
            trigger: ['blur', 'change']
          }],
          invoiceNo: [{
            required: true,
            message: '请填写票据单号',
            trigger: ['blur', 'change']
          }],
          chargeAmt: [{
            required: true,
            message: '请填写收费金额',
            trigger: ['blur', 'change']
          }],
          paymentMeth: [{
            required: true,
            message: '请选择缴费方式',
            trigger: ['blur', 'change']
          }],
          chargeType: [{
            required: true,
            message: '请选择收费类型',
            trigger: ['blur', 'change']
          }],
        },
        pickerShow: false,
        gsShow: false,
        datetimeShow: false,
        dataTimeValue: Number(new Date()),
        columns: [],
        gsColumns: [],
        regionName: [],
        groupName: [],
        companyName: [],
        companyCode: [],
        currentName: "", //弹窗后赋值name
        companyOption: [],
        fileList: [],
        attachmentList: [],
        // 基本信息
        basisData: [{
          label: '财年',
          placeholder: "请选择财年",
          type: "date",
          required: true,
          key: "fiscalYear",
        }, {
          label: '收费人员',
          placeholder: "请输入",
          type: "input",
          required: true,
          key: "billingPersonName",
        }, {
          label: '兼职/全职',
          placeholder: "请选择",
          type: "select",
          dict: "sys_mc_job_nature",
          key: "jobNature",
          required: true
        }, {
          label: '入户时间',
          placeholder: "请选择",
          type: "date",
          required: true,
          key: "entryTime"
        }, {
          label: '项目公司',
          placeholder: "请选择",
          type: "select",
          required: true,
          key: "company"
        }, {
          label: '村(小区)',
          placeholder: "请选择",
          type: "select",
          required: true,
          key: "vlgOrCmty"
        }, {
          label: '户名',
          placeholder: "请选择",
          type: "select",
          required: true,
          key: "userName",
        }, {
          label: '联系电话',
          placeholder: "请输入",
          type: "input",
          required: true,
          key: "userPhone"
        }, {
          label: '省/市/区/街道',
          placeholder: "请输入",
          type: "input",
          required: true,
          key: 'address'
        }, {
          label: '详细地址',
          placeholder: "请输入",
          type: "input",
          required: true,
          key: "userDetailedAddress"
        }],
        // 拜访信息
        visitData: [{
          label: '本次是否拜访',
          type: "radio",
          required: true,
          key: "isVisited",
          show: true,
        }, {
          label: '是否有意向',
          placeholder: "请选择",
          required: true,
          type: "select",
          key: "isIntent",
          show: true,
          dict: 'sys_cn_yn'
        }, {
          label: '房屋情况',
          placeholder: "请选择",
          required: true,
          type: "select",
          key: "houseCondition",
          dict: "sys_mc_visit_house",
          show: true,
        }, {
          label: '现用做饭能源',
          placeholder: "请选择",
          required: true,
          type: "select",
          key: "currentCookingEnergy",
          dict: "sys_mc_visit_energy",
          show: true,
        }, {
          label: '现用取暖能源',
          placeholder: "请选择",
          type: "select",
          key: "currentHeatingEnergy",
          dict: "sys_mc_visit_energy",
          show: true,
        }, {
          label: '家庭人口情况',
          placeholder: "请选择",
          type: "select",
          key: "familyMembers",
          dict: "sys_mc_visit_members",
          show: true,
        }, {
          label: '电冰箱',
          placeholder: "请选择",
          type: "select",
          key: "fridgeStatus",
          dict: 'sys_mc_visit_appliance_status',
          show: true,
        }, {
          label: '空调',
          placeholder: "请选择",
          type: "select",
          key: "acStatus",
          dict: 'sys_mc_visit_appliance_status',
          show: true,
        }, {
          label: '电视',
          placeholder: "请选择",
          type: "select",
          key: "tvStatus",
          dict: 'sys_mc_visit_appliance_status',
          show: true,
        }, {
          label: '洗衣机',
          placeholder: "请选择",
          type: "select",
          key: "washerStatus",
          dict: 'sys_mc_visit_appliance_status',
          show: true,
        }, {
          label: '热水器',
          placeholder: "请选择",
          type: "select",
          key: "waterHeaterStatus",
          dict: 'sys_mc_visit_appliance_status',
          show: true,
        }, {
          label: '光伏',
          placeholder: "请选择",
          type: "select",
          key: "pvSystemStatus",
          dict: 'sys_mc_visit_appliance_status',
          show: true,
        }, {
          label: '当前地址',
          placeholder: "请输入",
          type: "input",
          key: "visitDetailedAddress",
          show: true,
        }, {
          label: '上传图片',
          placeholder: "请选择",
          type: "file",
          key: 'fieldPhotoFile',
          show: true,
        }],
        // 决策人信息
        decisionMakersData: [{
          label: '是否获取决策人信息',
          type: "radio",
          required: true,
          key: "hasDm",
          show: true,
        }, {
          label: '决策人年龄',
          placeholder: "请输入",
          required: true,
          type: "input",
          key: "dmAge",
          show: true,
        }, {
          label: '决策人收入来源',
          placeholder: "请选择",
          required: true,
          type: "select",
          key: "dmIncomeSrc",
          dict: 'sys_mc_visit_dm_income',
          show: true,
        }, {
          label: '决策人联系方式',
          placeholder: "请输入",
          required: true,
          type: "input",
          key: "dmPhone",
          show: true,
        }],
        // 收费信息
        chargeData: [{
          label: '本次是否收费',
          type: "radio",
          required: true,
          key: "isCharged",
          show: true,
        }, {
          label: '用户编号',
          placeholder: "请输入",
          required: true,
          type: "input",
          key: "userCode",
          show: true,
        }, {
          label: '身份证号',
          placeholder: "请输入",
          required: true,
          type: "input",
          key: "userIdCard",
          show: true,
        }, {
          label: '票据单号',
          placeholder: "请输入",
          required: true,
          type: "input",
          key: "invoiceNo",
          show: true,
        }, {
          label: '收费金额',
          placeholder: "请输入",
          required: true,
          type: "input",
          key: "chargeAmt",
          show: true,
        }, {
          label: '缴费方式',
          placeholder: "请选择",
          required: true,
          type: "select",
          key: "paymentMeth",
          dict: 'sys_mc_payment_meth',
          show: true,
        }, {
          label: '收费类型',
          placeholder: "请选择",
          required: true,
          type: "select",
          key: "chargeType",
          dict: "sys_mc_charge_type",
          show: true,
        }],
        // 其他信息
        otherData: [{
          label: '备注',
          placeholder: "请输入",
          type: "input",
          key: 'remark'
        }, {
          label: '附件',
          type: "attachment",
          key: "attachmentFile"
        }, ]
      }
    },
    computed: {

    },
    onLoad(data) {
      this.init();
      console.log(data);
      if (data.objData) {
        let obj = JSON.parse(data.objData);
        this.model = {
          ...obj
        };
        this.fillInData();
      }
      if (data.operation) {
        if (data.operation === 'yd') {
          console.log('异动数据', JSON.parse(JSON.stringify(this.model)));
          this.btnText = "发起异动";
          this.operationStatus = "YD" //异动
        } else if (data.operation === 'edit') {
          this.btnText = "修改";
          console.log('修改数据', JSON.parse(JSON.stringify(this.model)));
          this.operationStatus = "BJ" //编辑
        } else {
          this.operationStatus = "TJ" //添加
        }
      }
    },
    methods: {
      // 编辑或异动需要填充数据
      async fillInData() {
        this.model.company = `${this.model.userProvince}`
        this.model.address =
          `${this.model.userProvince}${this.model.userCity}${this.model.userDistrict}${this.model.userStreet}`
        this.model.isCharged = this.model.isCharged === 'Y' ? '是' : '否';
        this.model.isIntent = this.model.isIntent === 'Y' ? '是' : '否';
        this.model.isVisited = this.model.isVisited === 'Y' ? '是' : '否';
        this.model.hasDm = this.model.hasDm === 'Y' ? '是' : '否';
        if (this.model.isCharged === '否') {
          this.chargeData.slice(1).map(item => {
            item.show = false;
          })
        }
        if (this.model.isVisited === '否') {
          this.visitData.slice(1).map(item => {
            item.show = false;
          })
        }
        if (this.model.hasDm === '否') {
          this.decisionMakersData.slice(1).map(item => {
            item.show = false;
          })
        }
        let uuid = this.model.attachmentFile;
        console.log(uuid);
        if (uuid) {
          let uuids = uuid.split(",");
          let data = {
            uuids: uuids
          }
          getMcFileList(data).then(res => {
            if (res.code === 200) {
              this.attachmentList = res.data
            }
          })
        }

      },
      async init() {
        console.log(this.$store);
        // 默认选是
        this.model.isCharged = '是';
        this.model.isVisited = '是';
        this.model.hasDm = '是';
        // 查询财年
        await this.getCurrentFiscalYear()
        await this.getCompanyCascader()
        let nickName = uni.getStorageSync("nickName");

        this.$set(this.model, 'billingPersonName', nickName)
        // console.log(this.model.billingPersonName);
      },
      async getCurrentFiscalYear() {
        let fiscalYear = (await getCurrentFiscalYear()).data;
        this.$set(this.model, 'fiscalYear', fiscalYear);
        console.log("当前财年", this.model.fiscalYear);
      },
      async getCompanyCascader() {
        this.companyOption = (await getCompanyCascader()).data;
        this.companyOption.forEach(item1 => {
          this.regionName.push(item1);
          item1.children.forEach(item2 => {
            this.groupName.push(item2);
            item2.children.forEach(item3 => {
              this.companyName.push(item3);
            });
          });
        });
        console.log("当前公司类", this.companyOption);
      },
      // 选择弹出层
      async handleSelect(item) {
        if (this.operationStatus === 'YD') {
          return
        }
        console.log(item);
        this.currentName = item.key;
        if (item.key === 'company') {
          this.gsColumns = [this.regionName, this.groupName, this.companyName];
          this.gsShow = true;
          return
          console.log("数据", this.columns);
        } else if (item.key === 'vlgOrCmty') {
          if (!this.model.company) {
            uni.$u.toast('请先选择项目公司');
            return
          }
          let data = {
            fiscalYear: this.model.fiscalYear,
            regionName: this.model.regionName,
            groupName: this.model.groupName,
            companyName: this.model.companyName,
            companyCode: this.model.companyCode
          }
          const result = await getVlgOrCmty(data);
          let col = result.data.map(item => ({
            value: item.vlgOrCmty,
            label: item.vlgOrCmty
          }));
          this.columns = [col];
        } else if (item.key === 'userName') {
          if (!this.model.vlgOrCmty) {
            uni.$u.toast('请先选择村(小区)');
            return
          }
          let data = {
            companyCode: this.model.companyCode,
            vlgOrCmty: this.model.vlgOrCmty
          }
          const result = await getMcVisitUser(data);
          let col = result.rows.map(item => ({
            value: item.userName,
            label: item.userName,
            obj: item
          }));
          this.columns = [col];
        } else {
          let dict = item.dict;
          let dictArr = this.getDictDatas(dict);
          this.columns = [dictArr];
        }
        this.pickerShow = true;
        console.log(this.columns);
        // console.log("字典数组", dictArr);
      },
      handleSFSelect(item) {
        this.currentName = item.key;
        let dict = item.dict;
        let dictArr = this.getDictDatas(dict);
        this.columns = [dictArr];
        this.pickerShow = true;
      },
      changeHandler(e) {
        console.log(this.currentName);
        const {
          columnIndex,
          value,
          values, // values为当前变化列的数组内容
          index,
          // 微信小程序无法将picker实例传出来，只能通过ref操作
          picker = this.$refs.uPicker
        } = e
        console.log(e);
        // 当第一列值发生变化时，变化第二列(后一列)对应的选项
        let data2 = value[0].children;
        let data3 = data2[0].children;
        // picker为选择器this实例，变化第二列对应的选项
        this.gsColumns = [this.regionName, data2, data3]
        console.log("选择后", this.gsColumns);
      },
      // 选择弹出层确认
      confirm(e) {
        console.log("确认", e);
        if (this.currentName === 'company') {
          this.model[this.currentName] = `${e.value[2].label}`;
          this.model.regionName = e.value[0]?.value;
          this.model.groupName = e.value[1]?.value;
          this.model.companyName = e.value[2]?.label;
          this.model.companyCode = e.value[2]?.value;
        } else if (this.currentName === 'userName') {
          let data = e.value[0].obj
          this.model[this.currentName] = e.value[0].value
          this.model['userPhone'] = data.userPhone;
          this.model['userProvince'] = data.province;
          this.model['userCity'] = data.city;
          this.model['userDistrict'] = data.district;
          this.model['userStreet'] = data.street;
          this.model['userDetailedAddress'] = data.detailedAddress;
          this.model['address'] = `${data.province}${data.city}${data.district}${data.street}`;
        } else {
          this.model[this.currentName] = e.value[0].value
        }
        this.pickerShow = false;
      },
      // 项目公司独立弹窗,防止共用报错
      gsConfirm(e) {
        console.log("公司", e);
        if (this.currentName === 'company') {
          this.model[this.currentName] = `${e.value[2].label}`;
          this.model.regionName = e.value[0]?.value;
          this.model.groupName = e.value[1]?.value;
          this.model.companyName = e.value[2]?.label;
          this.model.companyCode = e.value[2]?.value;
        }
        this.gsShow = false;
      },
      // 拜访单选
      bfChange(e) {
        console.log(e);
        if (e === '否') {
          this.visitData.slice(1).map(item => {
            item.show = false;
          })
        } else {
          this.visitData.map(item => {
            item.show = true;
          })
        }
      },
      // 决策人单选
      jcrChange(e) {
        if (e === '否') {
          this.decisionMakersData.slice(1).map(item => {
            item.show = false;
          })
        } else {
          this.decisionMakersData.map(item => {
            item.show = true;
          })
        }
      },
      sfChange(e) {
        if (e === '否') {
          this.chargeData.slice(1).map(item => {
            item.show = false;
          })
        } else {
          this.chargeData.map(item => {
            item.show = true;
          })
        }
      },
      // 查询小区
      async getVlgOrCmty() {
        console.log("查询小区数据", this.columns);
      },
      // 选择时间弹出层
      handleDateTime(item) {
        if (this.operationStatus === 'YD') {
          return
        }
        if (item.key === 'fiscalYear') {
          return
        }
        this.currentName = item.key;
        this.datetimeShow = true;
        console.log(item);
      },
      // 时间弹出层确认
      dateConfirm(e) {
        let time = this.$u.timeFormat(e.value, 'yyyy-mm-dd');
        console.log("选择时间", time);
        this.model[this.currentName] = time;
        this.datetimeShow = false;
      },
      // 删除图片
      deletePic(event) {
        this.fileList.splice(event.index, 1)
      },
      // 新增图片
      async afterRead(event) {
        // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
        let lists = [].concat(event.file)
        let fileListLen = this.fileList.length
        lists.map((item) => {
          this.fileList.push({
            ...item,
            status: 'uploading',
            message: '上传中'
          })
        })
        for (let i = 0; i < lists.length; i++) {
          const result = await this.uploadFilePromise(lists[i].url)
          let item = this.fileList[fileListLen]
          this.fileList.splice(fileListLen, 1, Object.assign(item, {
            status: 'success',
            message: '',
            uuid: result.uuid,
            url: result
          }))
          fileListLen++
        }
        console.log(this.fileList);
      },
      uploadFilePromise(url) {
        return new Promise((resolve, reject) => {
          let a = uni.uploadFile({
            url: `${config.baseUrl}/schsf/mcFile/upload`,
            filePath: url,
            name: 'file',
            header: {
              Authorization: "Bearer " + uni.getStorageSync('ACCESS_TOKEN')
            },
            success: (res) => {
              console.log("上传结果", res);
              setTimeout(() => {
                if (res.statusCode === 200) {
                  let data = JSON.parse(res.data);
                  console.log("上传data", data.data[0]);
                  resolve(data.data[0])
                }
              }, 500)
            }
          });
        })
      },
      async uploadAttachment() {
        console.log("上传附件");
        uni.chooseFile({
          count: 1, //默认100
          extension: ['.doc', '.xlsx', '.docx'],
          success: async (res) => {
            let tempUrl = res.tempFilePaths[0]
            console.log(res);
            const result = await chargeFile.uploadFile(tempUrl);
            this.attachmentList.push(result);
            console.log(result);
          }
        });
      },
      // 重构提交数据，不影响表单数据
      copyMethods() {
        this.copyModel.fieldPhotoFile = this.fileList.map(item => item.uuid).join(",");
        this.copyModel.isCharged = this.copyModel.isCharged === '是' ? 'Y' : 'N';
        this.copyModel.isIntent = this.copyModel.isIntent === '是' ? 'Y' : 'N';
        this.copyModel.isVisited = this.copyModel.isVisited === '是' ? 'Y' : 'N';
        this.copyModel.hasDm = this.copyModel.hasDm === '是' ? 'Y' : 'N';
        this.copyModel.attachmentFile = this.attachmentList.map(item => item.uuid).join(",");
      },
      // 发起拜访或异动或者修改
      handleConfirm() {
        this.copyModel = {
          ...this.model
        };
        this.copyMethods();
        console.log('提交数据', JSON.parse(JSON.stringify(this.copyModel)));
        // 提交
        if (this.operationStatus === 'TJ') {
          this.$refs.uForm.validate().then(res => {
            this.$modal.confirm('确认发起当前这条记录?', '温馨提示').then(async () => {
              const result = await addMcVisit(this.copyModel);
              console.log(result);
              if (result.code === 200) {
                uni.$u.toast('发起成功');
                setTimeout(() => {
                  this.$goBack();
                }, 1000)
              }
            }).catch(() => {});
            // uni.$u.toast('校验通过')
          }).catch(errors => {
            console.log('校验失败', errors);
            // uni.$u.toast('校验失败')
          })
        } else if (this.operationStatus === 'YD') {
          this.handleYDConfirm();
        } else if (this.operationStatus === 'BJ') {
          this.handleEditConfirm();
        }
      },
      // 编辑提交
      handleEditConfirm() {
        this.$refs.uForm.validate().then(res => {
          this.$modal.confirm('确认修改这条记录?', '温馨提示').then(async () => {
            const result = await editMcVisit(this.copyModel);
            console.log(result);
            if (result.code === 200) {
              uni.$u.toast('修改成功');
              setTimeout(() => {
                this.$goBack();
              }, 1000)
            }
          }).catch(() => {});
          // uni.$u.toast('校验通过')
        }).catch(errors => {
          console.log('校验失败', errors);
          // uni.$u.toast('校验失败')
        })
      },
      // 提交异动
      async handleYDConfirm() {
        let that = this;
        that.$refs.uForm.validate().then(res => {
          that.$modal.confirm('确认发起异动?', '温馨提示').then(async () => {
            let data = {
              id: that.copyModel.id,
              userIdCard: that.copyModel.userIdCard,
              invoiceNo: that.copyModel.invoiceNo,
              chargeAmt: that.copyModel.chargeAmt,
              paymentMeth: that.copyModel.paymentMeth,
              chargeType: that.copyModel.chargeType,
              remark: that.copyModel.remark,
              attachmentFile: that.copyModel.attachmentFile
            }
            console.log("异动数据", data);
            const result = await modification(data);
            console.log(result);
            if (result.code === 200) {
              uni.$u.toast('异动成功');
              setTimeout(() => {
                that.$goBack();
              }, 1000)
            } else {
              uni.$u.toast(result.msg);
            }
          }).catch(() => {});
          // uni.$u.toast('校验通过')
        }).catch(errors => {
          console.log('校验失败', errors);
          // uni.$u.toast('校验失败')
        })
      },
    }
  }
</script>

<style lang="scss" scoped>
  .container {
    padding-bottom: 100rpx;
    background: #F2F4F3;
  }

  /deep/.u-input__content__field-wrapper__field {
    margin-right: 20rpx;
  }

  /deep/.u-upload__button {
    margin: 0;
  }

  .fixedBtnCss {
    position: fixed;
    bottom: 0;
    height: 100rpx;
    width: 100%;
    padding: 10rpx;
    background: #fff;
  }
</style>
